package com.ruoyi.djb.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.ruoyi.common.annotation.AdminLoginToken;
import com.ruoyi.common.annotation.PassToken;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.IpUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.common.utils.jwtUtils;
import com.ruoyi.common.utils.wxPay.WXPayConstants;
import com.ruoyi.common.utils.wxPay.WXPayUtil;
import com.ruoyi.djb.domain.*;
import com.ruoyi.djb.mapper.*;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.*;

import static com.ruoyi.common.utils.DateUtils.YYYY_MM_DD_HH_MM_SS;
import static com.ruoyi.djb.config.Constants.*;

@Controller
@RequestMapping("admin")
public class AdminController extends BaseController {

    private static final String AlgorithmValue="jsdfsdfDFDfsd2343dfFDF";

    @Resource
    private DjbVersionMapper versionMapper;
    @Resource
    private DjbAdminMapper adminMapper;
    @Resource
    private DjbBuildingMapper buildingMapper;
    @Resource
    private DjbGateMapper gateMapper;
    @Resource
    private DjbDistrictMapper districtMapper;
    @Resource
    private DjbDistrictUserMapper districtUserMapper;
    @Resource
    private DjbRegistryMapper registryMapper;
    @Resource
    private DjbReleaseMapper releaseMapper;
    @Resource
    private DjbTagMapper tagMapper;
    @Resource
    private DjbUserMapper userMapper;
    @Resource
    private DjbUserRemindMapper userRemindMapper;
    @Resource
    private DjbDistrictBluetoothMapper bluetoothMapper;
    @Resource
    private DjbReasonMapper reasonMapper;
    @Resource
    private DjbPhoneCodeMapper phoneCodeMapper;
    @Resource
    private DjbUserLimitMapper userLimitMapper;
    @Resource
    private DjbChargeGradientMapper chargeGradientMapper;
    @Resource
    private DjbTradeMapper tradeMapper;
    @Resource
    private DjbSysConfigMapper djbSysConfigMapper;

    @Value("${djb.env}")
    private String env;

    /*登录*/
    @PostMapping("/Login")
    @ResponseBody
    @PassToken
    @RepeatSubmit
    public AjaxResult Login(@RequestParam("IMEI") String IMEI,
                            @RequestParam("version") String version,
                            @RequestParam("type") String type,
                            @RequestParam(value = "openId",required = false) String openId,
                            @RequestParam(value = "unionId",required = false) String unionId,
                            @RequestParam(value = "token",required = false) String token,
                            @RequestParam(value = "headUrl",required = false) String headUrl,
                            @RequestParam(value = "nickName",required = false) String nickName,
                            @RequestParam(value = "registrationId",required = false) String registrationId) {
        DjbAdmin admin;
        Map<String,Object> checkMap = new HashMap<>();
        checkMap.put("IMEI",IMEI);
        checkMap.put("version",version);
        checkMap.put("type",type);
        switch (type){
            case "t":
                checkMap.put("token",token);
                String s3 = checkRequestParameter(checkMap);
                if(!s3.isEmpty()){
                    return error("缺少参数："+s3);
                }
                try {
                    JWT.require(Algorithm.HMAC256(AlgorithmValue)).build().verify(token);
                } catch (JWTVerificationException e) {
                    return AjaxResult.error("TOKEN过期或失效");
                }
                int userId;
                try {
                    DecodedJWT jwt =JWT.decode(token);
                    Claim claim=jwt.getClaim("id");
                    userId = Integer.parseInt(claim.asString());
                } catch (JWTDecodeException j) {
                    return AjaxResult.error("TOKEN解析错误");
                }
                admin = adminMapper.selectDjbAdminById(userId);
                if (admin == null) {
                    return AjaxResult.error("用户不存在，请重新登录");
                }
                break;
            case "o":
                checkMap.put("openId",openId);
                String s4 = checkRequestParameter(checkMap);
                if(!s4.isEmpty()){
                    return error("缺少参数："+s4);
                }
                if(openId.trim().isEmpty()){
                    return AjaxResult.error("openId不能为空");
                }
                admin = adminMapper.selectDjbAdminByOpenId(openId);
                if (admin == null) {
                    admin = new DjbAdmin();
                    admin.setName(nickName);
                    admin.setOpenId(openId);
                    admin.setMobile("");
                    admin.setDistrictId(0);
                    admin.setDistrictName("");
                    admin.setType(0);
                    admin.setHeadUrl(headUrl);
                    admin.setStatus(0);
                    admin.setGateId(0);
                    admin.setGateName("");
                    admin.setIsPost(0);
                    admin.setReason("");
                    admin.setToken("");
                    admin.setVersion(version);
                    admin.setUnionId(unionId);
                    adminMapper.insertDjbAdmin(admin);
                }else if(admin.getUnionId().isEmpty()){
                    admin.setUnionId(unionId);
                    adminMapper.updateDjbAdmin(admin);
                }
                break;
            default:
                return AjaxResult.error("登录方式错误，请联系客服处理，错误码：E1001");
        }
        Map<String,Object> params = new HashMap<>();
        params.put("id",admin.getId());
        /*IMEI 设备唯一识别码，登录之后写入token保存到库中，更换手机之后生成另一个token更新库里的token,之前手机保存的token失效*/
        params.put("IMEI",IMEI);
        params.put("version",version);
        token = jwtUtils.getToken(params);
        admin.setToken(token);
        admin.setVersion(version);
        if(registrationId!=null && !registrationId.isEmpty()){
            admin.setRegistrationId(registrationId);
        }
        adminMapper.updateDjbAdmin(admin);
        JSONObject ret = new JSONObject();
        ret.put("admin",admin);
        ret.put("districtDetail",null);
        ret.put("gateList",null);
        ret.put("toVerifyAdmin",0);
        ret.put("toVerifyUser",0);
        if(admin.getDistrictId()!=0 && admin.getStatus()==SYS_STATUS_PASS){
            DjbDistrict djbDistrict = districtMapper.selectDjbDistrictById(admin.getDistrictId());
            ret.replace("districtDetail",djbDistrict);
            DjbGate djbGate = new DjbGate();
            djbGate.setDistrictId(admin.getDistrictId());
            List<DjbGate> djbGates = gateMapper.selectDjbGateList(djbGate);
            ret.replace("gateList",djbGates);
            if(admin.getType().equals(ADMIN_TYPE_ADMIN)||admin.getType().equals(ADMIN_TYPE_WUYE)||admin.getType().equals(ADMIN_TYPE_MANAGER_WUYE)){
                DjbAdmin query3 = new DjbAdmin();
                query3.setDistrictId(admin.getDistrictId());
                query3.setStatus(SYS_STATUS_TODO);
                List<DjbAdmin> djbAdmins = adminMapper.selectDjbAdminList(query3);
                ret.replace("toVerifyAdmin",djbAdmins.size());
                DjbDistrictUser districtUser = new DjbDistrictUser();
                districtUser.setDistrictId(admin.getDistrictId());
                districtUser.setStatus(SYS_STATUS_TODO);
                List<DjbDistrictUser> djbDistrictUsers = districtUserMapper.selectDjbDistrictUserList(districtUser);
                ret.replace("toVerifyUser",djbDistrictUsers.size());
            }
        }
        return AjaxResult.success("登录成功",ret);
    }

    /*登录*/
    @PostMapping("/LoginPhone")
    @ResponseBody
    @PassToken
    @RepeatSubmit
    public AjaxResult LoginPhone(@RequestParam("IMEI") String IMEI,
                            @RequestParam("version") String version,
                            @RequestParam("type") String type,
                            @RequestParam(value = "openId",required = false) String openId,
                            @RequestParam(value = "phone",required = false) String phone,
                            @RequestParam(value = "password",required = false) String password,
                            @RequestParam(value = "unionId",required = false) String unionId,
                            @RequestParam(value = "headUrl",required = false) String headUrl,
                            @RequestParam(value = "nickName",required = false) String nickName) {
        DjbAdmin admin;
        Map<String,Object> checkMap = new HashMap<>();
        checkMap.put("IMEI",IMEI);
        checkMap.put("version",version);
        checkMap.put("type",type);
        checkMap.put("openId",openId);
        String s4 = checkRequestParameter(checkMap);
        if(!s4.isEmpty()){
            return error("缺少参数："+s4);
        }
        if(phone.trim().isEmpty()){
            return AjaxResult.error("phone不能为空");
        }
        openId="ogVw56jTuripkqLiuPd1fomuq69M";
        admin = adminMapper.selectDjbAdminByOpenId(openId);
        if (admin == null) {
            admin = new DjbAdmin();
            admin.setName(nickName);
            admin.setOpenId(openId);
            admin.setMobile("");
            admin.setDistrictId(0);
            admin.setDistrictName("");
            admin.setType(0);
            admin.setHeadUrl(headUrl);
            admin.setStatus(0);
            admin.setGateId(0);
            admin.setGateName("");
            admin.setIsPost(0);
            admin.setReason("");
            admin.setToken("");
            admin.setVersion(version);
            admin.setUnionId(unionId);
            adminMapper.insertDjbAdmin(admin);
        }else if(admin.getUnionId().isEmpty()){
            admin.setUnionId(unionId);
            adminMapper.updateDjbAdmin(admin);
        }
        Map<String,Object> params = new HashMap<>();
        params.put("id",admin.getId());
        /*IMEI 设备唯一识别码，登录之后写入token保存到库中，更换手机之后生成另一个token更新库里的token,之前手机保存的token失效*/
        params.put("IMEI",IMEI);
        params.put("version",version);
        String token = jwtUtils.getToken(params);
        admin.setToken(token);
        admin.setVersion(version);
        adminMapper.updateDjbAdmin(admin);
        JSONObject ret = new JSONObject();
        ret.put("admin",admin);
        if(admin.getDistrictId()!=0 && admin.getStatus()==SYS_STATUS_PASS){
            DjbDistrict djbDistrict = districtMapper.selectDjbDistrictById(admin.getDistrictId());
            ret.put("districtDetail",djbDistrict);
            DjbGate djbGate = new DjbGate();
            djbGate.setDistrictId(admin.getDistrictId());
            List<DjbGate> djbGates = gateMapper.selectDjbGateList(djbGate);
            ret.put("gateList",djbGates);
//            if(admin.getType().equals(ADMIN_TYPE_ADMIN)||admin.getType().equals(ADMIN_TYPE_WUYE)||admin.getType().equals(ADMIN_TYPE_MANAGER)){
//                DjbAdmin query3 = new DjbAdmin();
//                query3.setDistrictId(admin.getDistrictId());
//                query3.setStatus(SYS_STATUS_TODO);
//                List<DjbAdmin> djbAdmins = adminMapper.selectDjbAdminList(query3);
//                ret.put("toVerifyAdmin",djbAdmins.size());
//                DjbDistrictUser districtUser = new DjbDistrictUser();
//                districtUser.setDistrictId(admin.getDistrictId());
//                districtUser.setStatus(SYS_STATUS_TODO);
//                List<DjbDistrictUser> djbDistrictUsers = districtUserMapper.selectDjbDistrictUserList(districtUser);
//                ret.put("toVerifyUser",djbDistrictUsers.size());
//            }
        }
        return AjaxResult.success("登录成功",ret);
    }

    /*获取个人信息*/
    @GetMapping("/getAdminInfo")
    @ResponseBody
    @AdminLoginToken
    public AjaxResult getAdminInfo(HttpServletRequest request) {
        DjbAdmin admin = (DjbAdmin) request.getAttribute("admin");
        JSONObject ret = new JSONObject();
        ret.put("admin",admin);
        ret.put("districtDetail",null);
        ret.put("gateList",null);
        ret.put("toVerifyAdmin",0);
        ret.put("toVerifyUser",0);
        if(admin.getDistrictId()!=0 && admin.getStatus()==SYS_STATUS_PASS){
            DjbDistrict djbDistrict = districtMapper.selectDjbDistrictById(admin.getDistrictId());
            ret.put("districtDetail",djbDistrict);
            DjbGate djbGate = new DjbGate();
            djbGate.setDistrictId(admin.getDistrictId());
            List<DjbGate> djbGates = gateMapper.selectDjbGateList(djbGate);
            ret.put("gateList",djbGates);
            if(admin.getType().equals(ADMIN_TYPE_ADMIN)||admin.getType().equals(ADMIN_TYPE_WUYE)||admin.getType().equals(ADMIN_TYPE_MANAGER_WUYE)){
                DjbAdmin query3 = new DjbAdmin();
                query3.setDistrictId(admin.getDistrictId());
                query3.setStatus(SYS_STATUS_TODO);
                List<DjbAdmin> djbAdmins = adminMapper.selectDjbAdminList(query3);
                ret.put("toVerifyAdmin",djbAdmins.size());

                List<DjbDistrictUser> djbDistrictUsers = new ArrayList<>();
                List<Integer> integers = queryBuilding2(admin.getId());
                for(Integer buildingId : integers){
                    DjbDistrictUser districtUser = new DjbDistrictUser();
                    districtUser.setDistrictId(admin.getDistrictId());
                    districtUser.setStatus(SYS_STATUS_TODO);
                    districtUser.setBuilding(buildingId);
                    List<DjbDistrictUser> djbDistrictUsersTmp = districtUserMapper.selectDjbDistrictUserList(districtUser);
                    djbDistrictUsers.addAll(djbDistrictUsersTmp);
                }
                ret.put("toVerifyUser",djbDistrictUsers.size());
            }
        }
        return AjaxResult.success("查询成功",ret);
    }

    /*登记列表*/
    @GetMapping("/registryList")
    @ResponseBody
    @AdminLoginToken
    public AjaxResult registryList(HttpServletRequest request) throws InterruptedException {
        DjbAdmin admin = (DjbAdmin) request.getAttribute("admin");
        if(admin.getType()==ADMIN_TYPE_GATE&&admin.getIsPost()==SYS_NO){
            return AjaxResult.warn("无记录");
        }
        List<DjbRegistry> djbRegistries;
        DjbRegistry query = new DjbRegistry();
        query.setDistrictId(admin.getDistrictId());
        if(admin.getType().equals(ADMIN_TYPE_GATE)){
            query.setGateId(admin.getGateId());
            DjbGate gate = gateMapper.selectDjbGateById(admin.getGateId());
            Integer registeType = gate.getRegisteType();
            if(registeType==1){
                query.setUserType(USER_TYPE_PERSON);
            }else if(registeType==2){
                query.setUserType(USER_TYPE_CAR);
            }
            djbRegistries= registryMapper.selectGateDjbRegistryList(query);
        }else if(admin.getType().equals(ADMIN_TYPE_WUYE)){
            List<Integer> integers = queryBuilding(admin.getId());
            if(integers.isEmpty()){
                return error("无记录");
            }
            //初始化需要得到的数组
            String[] array = new String[integers.size()];
            //使用for循环得到数组
            for(int i = 0; i < integers.size();i++){
                array[i] = String.valueOf(integers.get(i));
            }
            djbRegistries = registryMapper.selectWuyeDjbRegistryList(array);
        }else{
            djbRegistries= registryMapper.selectAdminDjbRegistryList(query);
        }
        for(int i=0;i<djbRegistries.size();i++){
            DjbRegistry tmp = djbRegistries.get(i);
            if(tmp.getType().equals(TYPE_TOMORROW_WHOLE)||tmp.getType().equals(TYPE_TOMORROW_ONE)){
                djbRegistries.remove(i);
                i--;
                continue;
            }
            DjbRelease release = new DjbRelease();
            if(tmp.getUserType()==USER_TYPE_PERSON){
                release.setMobile(tmp.getMobile());
            }else{
                release.setName(tmp.getName());
            }
            release.setDistrictId(admin.getDistrictId());
            List<DjbRelease> djbReleaseList = releaseMapper.selectDjbReleaseList(release);
            tmp.setRegHistoryNum(djbReleaseList.size());

            JSONObject tags=new JSONObject();
            DjbRelease release2 = new DjbRelease();
//            release2.setUserId(tmp.getUserId());
            if(tmp.getUserType()==USER_TYPE_PERSON){
                release2.setMobile(tmp.getMobile());
            }else{
                release2.setName(tmp.getName());
            }
            release2.setUserType(tmp.getUserType());
            List<DjbRelease> djbReleaseList1 = releaseMapper.selectHalfYearThreeTimeReleaseList(release2);
            for(DjbRelease tmp2: djbReleaseList1){
                if(!tmp2.getTag().isEmpty()){
                    String tag1 = tmp2.getTag();
                    tags.put(tag1,1);
                }
            }
            tmp.setTags(tags);
        }
        JSONObject ret =new JSONObject();
        ret.put("registryList",djbRegistries);
        return AjaxResult.success("查询成功",ret);
    }

    /*登记详情 暂时无用*/
    /*@GetMapping("/registryDetail")
    @ResponseBody
    @AdminLoginToken
    public AjaxResult registryDetail(HttpServletRequest request,int id) throws InterruptedException {
        DjbAdmin admin = (DjbAdmin) request.getAttribute("admin");
        if(admin.getType()==ADMIN_TYPE_GATE&&admin.getIsPost()==SYS_NO){
            return AjaxResult.warn("无记录");
        }
        List<DjbRegistry> djbRegistries;
        DjbRegistry query = new DjbRegistry();
        query.setDistrictId(admin.getDistrictId());
        if(admin.getType().equals(ADMIN_TYPE_GATE)){
            query.setGateId(admin.getGateId());
            djbRegistries= registryMapper.selectGateDjbRegistryList(query);
        }else if(admin.getType().equals(ADMIN_TYPE_WUYE)){
            List<Integer> integers = queryBuilding(admin.getId());
            if(integers.isEmpty()){
                return error("无记录");
            }
            //初始化需要得到的数组
            String[] array = new String[integers.size()];
            //使用for循环得到数组
            for(int i = 0; i < integers.size();i++){
                array[i] = String.valueOf(integers.get(i));
            }
            djbRegistries = registryMapper.selectWuyeDjbRegistryList(array);
        }else{
            djbRegistries= registryMapper.selectAdminDjbRegistryList(query);
        }
//        for(DjbRegistry tmp : djbRegistries){
//            new Thread(() -> {
//                DjbRelease release = new DjbRelease();
//                release.setName(tmp.getName());
//                List<DjbRelease> djbReleaseList = releaseMapper.selectDjbReleaseList(release);
//                tmp.setRegHistoryNum(djbReleaseList.size());
//                List<DjbTag> djbTags;
//                if(tmp.getUserType()==USER_TYPE_PERSON){
//                    djbTags = tagMapper.selectDjbTagByMobile(tmp.getMobile());
//                }else{
//                    djbTags = tagMapper.selectDjbTagByCar(tmp.getName());
//                }
//                JSONObject tags=new JSONObject();
//                for(DjbTag tag:djbTags){
//                    String tag1 = tag.getTag();
//                    if(tags.containsKey(tag1)){
//                        tags.put(tag1,tags.getIntValue(tag1)+1);
//                    }else{
//                        tags.put(tag1,1);
//                    }
//                }
//                tmp.setTags(tags);
//            }).start();
//        }
//        Thread.sleep(500);
        for(int i=0;i<djbRegistries.size();i++){
            DjbRegistry tmp = djbRegistries.get(i);
            if(tmp.getType().equals(TYPE_TOMORROW_WHOLE)||tmp.getType().equals(TYPE_TOMORROW_ONE)){
                djbRegistries.remove(i);
                i--;
                continue;
            }
            DjbRelease release = new DjbRelease();
            if(tmp.getUserType()==USER_TYPE_PERSON){
                release.setMobile(tmp.getMobile());
            }else{
                release.setName(tmp.getName());
            }
            release.setDistrictId(admin.getDistrictId());
            List<DjbRelease> djbReleaseList = releaseMapper.selectDjbReleaseList(release);
            tmp.setRegHistoryNum(djbReleaseList.size());


            DjbRelease release2 = new DjbRelease();
            release2.setUserId(tmp.getUserId());
//            if(tmp.getUserType()==USER_TYPE_PERSON){
//                release2.setMobile(tmp.getMobile());
//            }else{
//                release2.setName(tmp.getName());
//            }
            release2.setUserType(tmp.getUserType());
            List<DjbRelease> djbReleaseList1 = releaseMapper.selectHalfYearThreeTimeReleaseList(release2);
            JSONObject tags=new JSONObject();
            for(DjbRelease tmp2: djbReleaseList1){
                if(!tmp2.getTag().isEmpty()){
                    String tag1 = tmp2.getTag();
                    tags.put(tag1,1);
                }
            }

//            List<DjbTag> djbTags;
//            if(tmp.getUserType()==USER_TYPE_PERSON){
//                djbTags = tagMapper.selectDjbTagByMobile(tmp.getMobile(),admin.getDistrictId());
//            }else{
//                djbTags = tagMapper.selectDjbTagByCar(tmp.getName(),admin.getDistrictId());
//            }
//            for(DjbTag tag:djbTags){
//                String tag1 = tag.getTag();
////                if(tags.containsKey(tag1)){
////                    tags.put(tag1,tags.getIntValue(tag1)+1);
////                }else{
////                    tags.put(tag1,1);
////                }
//                tags.put(tag1,1);
//            }
            tmp.setTags(tags);
        }
        JSONObject ret =new JSONObject();
        ret.put("registryList",djbRegistries);
        return AjaxResult.success("查询成功",ret);
    }*/

    /*放行列表*/
    @GetMapping("/releaseList")
    @ResponseBody
    @AdminLoginToken
    public AjaxResult releaseList(HttpServletRequest request,Integer type) throws InterruptedException {
        DjbAdmin admin = (DjbAdmin) request.getAttribute("admin");
//        if(admin.getType()==ADMIN_TYPE_GATE&&admin.getIsPost()==SYS_NO){
//            return AjaxResult.warn("无记录");
//        }
        List<DjbRelease> djbReleaseList;
        DjbRelease query = new DjbRelease();
        query.setDistrictId(admin.getDistrictId());
        if(type!=null&&type==7){
            Calendar calendar = Calendar.getInstance();
            Date date = DateUtils.getNowDate();
            calendar.setTime(date);
            calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
            /*今天0点*/
            Date todayZero = calendar.getTime();
            query.setCreateTime(DateUtils.addDays(todayZero,-6));
        }
        if(admin.getType().equals(ADMIN_TYPE_GATE)){
            djbReleaseList= releaseMapper.selectGateDjbReleaseList(query);
        }else if(admin.getType().equals(ADMIN_TYPE_WUYE)){
            List<Integer> integers = queryBuilding2(admin.getId());
            if(integers.isEmpty()){
                return error("还未绑定楼座");
            }
            //初始化需要得到的数组
            String[] array = new String[integers.size()];
            //使用for循环得到数组
            for(int i = 0; i < integers.size();i++){
                array[i] = String.valueOf(integers.get(i));
            }
            djbReleaseList = releaseMapper.selectAdminWuyeReleaseList(array,query);
        }else{
            djbReleaseList= releaseMapper.selectAdminDjbReleaseList(query);
        }

        for(DjbRelease tmp : djbReleaseList){
            tmp.setRegHistoryNum(tmp.getVisitNum());
        }
        JSONObject ret =new JSONObject();
        ret.put("releaseList",djbReleaseList);
        return AjaxResult.success("查询成功",ret);
    }

    /*更多放行列表*/
    @GetMapping("/releaseListMore")
    @ResponseBody
    @AdminLoginToken
    public AjaxResult releaseListMore(HttpServletRequest request,int id){
        DjbAdmin admin = (DjbAdmin) request.getAttribute("admin");
        DjbRelease tmp = releaseMapper.selectDjbReleaseById(id);
        DjbRelease release = new DjbRelease();
        if(tmp.getUserType()==USER_TYPE_PERSON){
            release.setMobile(tmp.getMobile());
        }else{
            release.setName(tmp.getName());
        }
        release.setDistrictId(tmp.getDistrictId());
        List<DjbRelease> djbReleaseList = releaseMapper.selectDjbReleaseList(release);
        JSONObject ret =new JSONObject();
        ret.put("releaseList",djbReleaseList);
        return AjaxResult.success("查询成功",ret);
    }

    /*放行详情*/
    @GetMapping("/releaseDetail")
    @ResponseBody
    @AdminLoginToken
    public AjaxResult releaseDetail(HttpServletRequest request,int id) throws InterruptedException {
        DjbAdmin admin = (DjbAdmin) request.getAttribute("admin");
        DjbRelease release = releaseMapper.selectDjbReleaseById(id);
        DjbRelease release2 = new DjbRelease();
        if(release.getUserType()==USER_TYPE_PERSON){
            release2.setMobile(release.getMobile());
        }else{
            release2.setName(release.getName());
        }
        release2.setDistrictId(release.getDistrictId());
        List<DjbRelease> djbReleases = releaseMapper.selectDjbReleaseList(release2);
        release.setRegHistoryNum(djbReleases.size());
        JSONObject ret =new JSONObject();
        ret.put("releaseDetail",release);
        return AjaxResult.success("查询成功",ret);
    }

    /*搜索列表*/
    @GetMapping("/searchList")
    @ResponseBody
    @AdminLoginToken
    public AjaxResult searchList(HttpServletRequest request) throws InterruptedException{
        DjbAdmin admin = (DjbAdmin) request.getAttribute("admin");
        List<DjbRegistry> djbRegistries=new ArrayList<>();
        if(!(admin.getType()==ADMIN_TYPE_GATE&&admin.getIsPost()==SYS_NO)){
            DjbRegistry query = new DjbRegistry();
            query.setDistrictId(admin.getDistrictId());
            if(admin.getType().equals(ADMIN_TYPE_GATE)){
                query.setGateId(admin.getGateId());
                djbRegistries= registryMapper.selectGateDjbRegistryList(query);
            }else{
                djbRegistries= registryMapper.selectAdminDjbRegistryList(query);
            }
        }
        for(int i=0;i<djbRegistries.size();i++){
            DjbRegistry tmp = djbRegistries.get(i);
            if(tmp.getType().equals(TYPE_TOMORROW_WHOLE)||tmp.getType().equals(TYPE_TOMORROW_ONE)){
                djbRegistries.remove(i);
                i--;
                continue;
            }
            DjbRelease release = new DjbRelease();
            if(tmp.getUserType()==USER_TYPE_PERSON){
                release.setMobile(tmp.getMobile());
            }else{
                release.setName(tmp.getName());
            }
            release.setDistrictId(admin.getDistrictId());
            List<DjbRelease> djbReleaseList = releaseMapper.selectDjbReleaseList(release);
            tmp.setRegHistoryNum(djbReleaseList.size());
            List<DjbTag> djbTags;
            if(tmp.getUserType()==USER_TYPE_PERSON){
                djbTags = tagMapper.selectDjbTagByMobile(tmp.getMobile(),admin.getDistrictId());
            }else{
                djbTags = tagMapper.selectDjbTagByCar(tmp.getName(),admin.getDistrictId());
            }
            JSONObject tags=new JSONObject();
            for(DjbTag tag:djbTags){
                String tag1 = tag.getTag();
//                if(tags.containsKey(tag1)){
//                    tags.put(tag1,tags.getIntValue(tag1)+1);
//                }else{
//                    tags.put(tag1,1);
//                }
                tags.put(tag1,1);
            }
            tmp.setTags(tags);
        }
        JSONObject ret =new JSONObject();

        List<DjbRelease> djbReleaseList;
        DjbRelease query2 = new DjbRelease();
        query2.setDistrictId(admin.getDistrictId());
        if(admin.getType().equals(ADMIN_TYPE_GATE)){
            query2.setReleaseId(admin.getId());
            djbReleaseList= releaseMapper.selectGateDjbReleaseList(query2);
        }else{
            djbReleaseList= releaseMapper.selectAdminDjbReleaseList(query2);
        }
//        for(DjbRelease tmp : djbReleaseList){
//            DjbRelease release = new DjbRelease();
//            if(tmp.getUserType()==USER_TYPE_PERSON){
//                release.setMobile(tmp.getMobile());
//            }else{
//                release.setName(tmp.getName());
//            }
//            release.setDistrictId(admin.getDistrictId());
//            List<DjbRelease> djbReleases = releaseMapper.selectDjbReleaseList(release);
//            tmp.setRegHistoryNum(djbReleases.size());
//        }

        ArrayList<Map<String,Object>> list = new ArrayList<>();
        for(DjbRegistry tmp : djbRegistries){
            Map<String,Object> map = new HashMap<>();
            map.put("id",tmp.getId());
            map.put("userId",tmp.getUserId());
            map.put("name",tmp.getName());
            map.put("mobile",tmp.getMobile());
            map.put("districtId",tmp.getDistrictId());
            map.put("gateId",tmp.getGateId());
            map.put("address",tmp.getAddress());
            map.put("reason",tmp.getReason());
            map.put("type",tmp.getType());
            map.put("releaseId",tmp.getReleaseId());
            map.put("releaseTime",tmp.getReleaseTime());
            map.put("status",tmp.getStatus());
            map.put("createType",tmp.getCreateType());
            map.put("createName",tmp.getCreateName());
            map.put("releaseName",tmp.getReleaseName());
            map.put("tags",tmp.getTags());
            map.put("userType",tmp.getUserType());
            map.put("regHistoryNum",tmp.getRegHistoryNum());
            map.put("createTime",tmp.getCreateTime());
            map.put("flag",1);
            map.put("tag","");
            map.put("images","");
            list.add(map);
        }
        for(DjbRelease tmp : djbReleaseList){
            Map<String,Object> map = new HashMap<>();
            map.put("id",tmp.getId());
            map.put("userId",tmp.getUserId());
            map.put("name",tmp.getName());
            map.put("mobile",tmp.getMobile());
            map.put("districtId",tmp.getDistrictId());
            map.put("gateId",tmp.getGateId());
            map.put("address",tmp.getAddress());
            map.put("reason",tmp.getReason());
            map.put("type",tmp.getType());
            map.put("releaseId",tmp.getReleaseId());
            map.put("releaseTime",tmp.getReleaseTime());
            map.put("status",tmp.getStatus());
            map.put("createType",tmp.getCreateType());
            map.put("createName",tmp.getCreateName());
            map.put("releaseName",tmp.getReleaseName());
            map.put("tags",tmp.getTags());
            map.put("userType",tmp.getUserType());
            map.put("regHistoryNum",tmp.getVisitNum());
            map.put("createTime",tmp.getCreateTime());
            map.put("flag",2);
            map.put("tag",tmp.getTag());
            map.put("images",tmp.getImages());
            list.add(map);
        }
        ret.put("unionList",list);
        return AjaxResult.success("查询成功",ret);
    }

    /*登记放行*/
    @PutMapping("/registryRelease")
    @ResponseBody
    @AdminLoginToken
    public AjaxResult registryRelease(HttpServletRequest request,Integer id){
        DjbAdmin admin = (DjbAdmin) request.getAttribute("admin");
        if(admin.getType().equals(ADMIN_TYPE_GATE)&&admin.getIsPost()==SYS_NO){
            return error("您已离岗");
        }
        DjbRegistry registry = registryMapper.selectDjbRegistryById(id);
        if(registry==null){
            return error("记录不存在");
        }
        if(registry.getStatus().equals(SYS_STATUS_PASS)){
            return error("该登记已放行");
        }
        if(registry.getStatus().equals(SYS_STATUS_EXPIRE)){
            return error("该登记已过期");
        }
        if(registry.getStatus().equals(SYS_STATUS_WASTE)){
            return error("该登记已作废");
        }
        if(registry.getStatus().equals(SYS_STATUS_WRONG)){
            return error("该登记已纠错");
        }
        if(registry.getStatus().equals(SYS_STATUS_REBUT)){
            return error("该登记已驳回");
        }
        if(registry.getType().equals(TYPE_TOMORROW_ONE)||registry.getType().equals(TYPE_TOMORROW_WHOLE)){
            return error("该登记属于明日，请刷新重试");
        }
        if(registry.getType().equals(TYPE_TODAY_ONE)||registry.getType().equals("夜间场景")){
            registry.setStatus(SYS_YES);
        }
        registry.setReleaseId(admin.getId());
        registry.setReleaseName(admin.getName());
        registry.setReleaseTime(DateUtils.getNowDate());
        registryMapper.updateDjbRegistry(registry);
        /*创建放行记录*/
        DjbRelease release = new DjbRelease();
        release.setUserId(registry.getUserId());
        release.setName(registry.getName());
        release.setMobile(registry.getMobile());
        release.setDistrictId(registry.getDistrictId());
        release.setGateId(registry.getGateId());
        if(registry.getGateId()==0&&admin.getType().equals(ADMIN_TYPE_GATE)&&admin.getGateId()!=null){
            release.setGateId(admin.getGateId());
        }
        release.setAddress(registry.getAddress());
        release.setReason(registry.getReason());
        release.setType(registry.getType());
        release.setReleaseId(registry.getReleaseId());
        release.setReleaseName(registry.getReleaseName());
        release.setReleaseTime(registry.getReleaseTime());
        release.setStatus(SYS_YES);
        release.setCreateType(registry.getCreateType());
        release.setCreateName(registry.getCreateName());
        release.setCreateTime(registry.getCreateTime());
        release.setCreateBy(registry.getCreateBy());
        release.setUserType(registry.getUserType());
        release.setBuilding(registry.getBuilding());
        release.setUnit(registry.getUnit());
        release.setFloor(registry.getFloor());
        release.setRoom(registry.getRoom());
        release.setTag("");
        release.setExamName(registry.getExamName());
        DjbRelease release2 = new DjbRelease();
        if(registry.getUserType()==USER_TYPE_PERSON){
            release2.setMobile(registry.getMobile());
        }else{
            release2.setName(registry.getName());
        }
        release2.setDistrictId(admin.getDistrictId());
        List<DjbRelease> djbReleases = releaseMapper.selectDjbReleaseList(release2);
        release.setVisitNum(djbReleases.size()+1);
        release.setRegId(registry.getId());
        release.setDepartment(registry.getDepartment());
        release.setRemark(registry.getRemark());
        release.setIdNumber(registry.getIdNumber());
        release.setDistrictName(registry.getDistrictName());
        release.setVisitPerson(registry.getVisitPerson());
        release.setVisitPersonId(registry.getVisitPersonId());
        releaseMapper.insertDjbRelease(release);
        /*如果放行的是车辆，且小区开了最大车辆限制,则车辆数加1*/
        DjbDistrict djbDistrict = districtMapper.selectDjbDistrictById(admin.getDistrictId());
        if(registry.getUserType()==1){
            if(djbDistrict.getMaxCar()!=0){
                djbDistrict.setCurrentCar(djbDistrict.getCurrentCar()+1);
                districtMapper.updateDjbDistrict(djbDistrict);
            }
            /*发送入场通知短信*/
            if(djbDistrict.getVipIncomeSms()==SYS_YES&&djbDistrict.getBalance()>10){
                sendIncomeSMS(release.getMobile(),release.getName(),release.getAddress(),djbDistrict.getVipIncomeSmsId(),djbDistrict);
            }
        }
        new Thread(() -> {
            /*发送消息通知*/
            if(registry.getCreateType().equals(CREATE_TYPE_USER)){
                //住户登记访客信息，访客来访门卫放行后，该住户会收到访客来访通知
                Integer userId = registry.getUserId();
                DjbUser djbUser = userMapper.selectDjbUserById(userId);
                if(djbUser!=null&&djbUser.getOpenId2()!=null&&!djbUser.getOpenId2().isEmpty()){
                    sendVisitArrived(djbUser.getOpenId2(),registry.getName(),registry.getMobile(),registry.getAddress(),registry.getReason(),registry.getType());
                }
            }else{//当访客登记，物业登记，门卫登记访客信息，访客来访门卫放行后，只有该户户主能收到访客来访通知
                /*有拜访人 拜访人接受*/
                if(registry.getVisitPerson()!=null && !registry.getVisitPerson().isEmpty() && registry.getVisitPersonId()!=null){
                    DjbUser djbUser = userMapper.selectDjbUserById(registry.getVisitPersonId());
                    if(djbUser!=null&&djbUser.getOpenId2()!=null&&!djbUser.getOpenId2().isEmpty()){
                        sendVisitArrived(djbUser.getOpenId2(),registry.getName(),registry.getMobile(),registry.getAddress(),registry.getReason(),registry.getType());
                    }
                }else{
                    //找业主
                    Integer building = registry.getBuilding();
                    DjbDistrictUser districtUser = new DjbDistrictUser();
                    districtUser.setDistrictId(registry.getDistrictId());
                    if(djbDistrict.getType()==BUILDING_TYPE_BUILD){
                        Integer unit = registry.getUnit();
                        Integer floor = registry.getFloor();
                        Integer room = registry.getRoom();
                        if(building!=null&&unit!=null&&floor!=null&&room!=null){
                            //找业主
                            districtUser.setBuilding(building);
                            districtUser.setUnit(unit);
                            districtUser.setFloor(floor);
                            districtUser.setRoom(room);
                            List<DjbDistrictUser> djbDistrictUsers = districtUserMapper.selectDjbDistrictUserList(districtUser);
                            for(DjbDistrictUser tmp: djbDistrictUsers){
                                if(tmp.getType().equals(0)||tmp.getStatus().equals(SYS_STATUS_TODO)) continue;
                                DjbUser djbUser = userMapper.selectDjbUserById(tmp.getUserId());
                                if(djbUser!=null&&djbUser.getOpenId2()!=null&&!djbUser.getOpenId2().isEmpty()){
                                    sendVisitArrived(djbUser.getOpenId2(),registry.getName(),registry.getMobile(),registry.getAddress(),registry.getReason(),registry.getType());
                                }
                            }
                        }
                    }else if(djbDistrict.getType()==BUILDING_TYPE_DEPARTMENT||djbDistrict.getType()==BUILDING_TYPE_COMPANY){
                        if(building!=null){
                            //找部门主管或前台
                            districtUser.setBuilding(building);
                            List<DjbDistrictUser> djbDistrictUsers = districtUserMapper.selectDjbDistrictUserList(districtUser);
                            for(DjbDistrictUser tmp: djbDistrictUsers){
                                if(tmp.getType().equals(0)||tmp.getStatus().equals(SYS_STATUS_TODO)) continue;
                                DjbUser djbUser = userMapper.selectDjbUserById(tmp.getUserId());
                                if(djbUser!=null&&djbUser.getOpenId2()!=null&&!djbUser.getOpenId2().isEmpty()){
                                    sendVisitArrived(djbUser.getOpenId2(),registry.getName(),registry.getMobile(),registry.getAddress(),registry.getReason(),registry.getType());
                                }
                            }
                        }
                    }
                }
            }
        }).start();
        return AjaxResult.success("放行成功");
    }

    /*登记失效*/
    @PutMapping("/registryExpire")
    @ResponseBody
    @AdminLoginToken
    public AjaxResult registryExpire(HttpServletRequest request,Integer id,String reason){
        DjbAdmin admin = (DjbAdmin) request.getAttribute("admin");
        if(admin.getType().equals(ADMIN_TYPE_GATE)&&admin.getIsPost()==SYS_NO){
            return error("您已离岗");
        }
        DjbRegistry registry = registryMapper.selectDjbRegistryById(id);
        if(registry==null){
            return error("记录不存在");
        }
        if(!registry.getStatus().equals(SYS_STATUS_TODO)){
            return error("登记状态已改变，请刷新后重试");
        }
        registry.setStatus(SYS_STATUS_WASTE);
        registryMapper.updateDjbRegistry(registry);
        /*发送消息通知*/
        DjbUser djbUser = userMapper.selectDjbUserById(registry.getUserId());
        /*查询是否订阅通知*/
        DjbUserRemind remind = new DjbUserRemind();
        remind.setRegistryId(registry.getId());
        remind.setUserId(registry.getUserId());
        remind.setSend(0);
        List<DjbUserRemind> djbUserReminds = userRemindMapper.selectDjbUserRemindList(remind);
        if(!djbUserReminds.isEmpty()){
            DjbUserRemind remind1 = djbUserReminds.get(0);
            if(registry.getCreateType()==CREATE_TYPE_USER){
                if(djbUser.getOpenId2()!=null && !djbUser.getOpenId2().isEmpty()){
                    sendGZHRegExpire(djbUser.getOpenId2(),registry.getName(),registry.getMobile(),registry.getAddress(),reason);
                    remind1.setSend(1);
                    userRemindMapper.updateDjbUserRemind(remind1);
                }
            }else if(registry.getCreateType()==CREATE_TYPE_VISITOR){
                if(djbUser.getOpenId()!=null && !djbUser.getOpenId().isEmpty()){
                    sendXCXRegExpire(djbUser.getOpenId(),registry.getName(),registry.getMobile(),registry.getAddress(),reason);
                    remind1.setSend(1);
                    userRemindMapper.updateDjbUserRemind(remind1);
                }
            }
        }
        return success("失效成功");
    }

    /*登记驳回*/
    @PutMapping("/registryRebut")
    @ResponseBody
    @AdminLoginToken
    public AjaxResult registryRebut(HttpServletRequest request,Integer id){
        DjbAdmin admin = (DjbAdmin) request.getAttribute("admin");
        if(admin.getType().equals(ADMIN_TYPE_GATE)&&admin.getIsPost()==SYS_NO){
            return error("您已离岗");
        }
        DjbRegistry registry = registryMapper.selectDjbRegistryById(id);
        if(registry==null){
            return error("记录不存在");
        }
        if(!registry.getStatus().equals(SYS_STATUS_TODO)){
            return error("登记状态已改变，请刷新后重试");
        }
        if(registry.getCreateType().equals(CREATE_TYPE_VISITOR)){
            registry.setStatus(SYS_STATUS_REBUT);
        }else{
            registry.setStatus(SYS_STATUS_WASTE);
        }
        registryMapper.updateDjbRegistry(registry);
        return success("驳回成功");
    }

    /*登记审核通过*/
    @PutMapping("/ExamRegistryPass")
    @ResponseBody
    @AdminLoginToken
    public AjaxResult ExamRegistryPass(HttpServletRequest request,Integer id){
        DjbAdmin admin = (DjbAdmin) request.getAttribute("admin");
        if(admin.getType().equals(ADMIN_TYPE_GATE)){
            return error("您无此权限");
        }
        DjbRegistry registry = registryMapper.selectDjbRegistryById(id);
        if(registry==null){
            return error("记录不存在");
        }
        if(registry.getStatus().equals(SYS_NO)){
            return error("该登记已通过");
        }
        registry.setStatus(SYS_NO);
        registry.setExamFlag("审核");
        registry.setExamName(admin.getName());
        registryMapper.updateDjbRegistry(registry);
        DjbUser djbUser;
        if(registry.getCreateType()==CREATE_TYPE_USER&&registry.getInputId()!=null){
            djbUser = userMapper.selectDjbUserById(registry.getInputId());
        }else{
            djbUser = userMapper.selectDjbUserById(registry.getUserId());
        }
        if(djbUser!=null&&djbUser.getOpenId2()!=null&&!djbUser.getOpenId2().isEmpty()){
            sendExamPassNotice(djbUser.getOpenId2(), registry.getName(), registry.getMobile(), registry.getAddress(), registry.getId(),registry.getType(),registry.getReason(),"user",djbUser.getId());
        }else{
            sendUserExamPass(djbUser.getOpenId(),registry.getName(), registry.getMobile(), registry.getAddress(),registry.getReason());
        }
        return success("通过成功");
    }

    /*内部登记*/
    @PutMapping("/registryAdd")
    @ResponseBody
    @AdminLoginToken
    public AjaxResult registryAdd(HttpServletRequest request,
                                  String name,
                                  String mobile,
                                  String address,
                                  String reason,
                                  String type,
                                  Integer userType,
                                  Integer building,
                                  Integer unit,
                                  Integer floor,
                                  Integer room,
                                  String department,
                                  String remark,
                                  String idNumber,
                                  String visitPerson,
                                  Integer visitPersonId){
        DjbAdmin admin = (DjbAdmin) request.getAttribute("admin");
        if(admin.getType().equals(ADMIN_TYPE_GATE)&&admin.getIsPost()==SYS_NO){
            return error("您已离岗");
        }
        DjbRegistry check = new DjbRegistry();
        check.setUserType(userType);
        if(userType==USER_TYPE_PERSON){
            check.setMobile(mobile);
        }else{
            check.setName(name);
        }
        check.setExamFlag("审核");
        check.setDistrictId(admin.getDistrictId());
        List<DjbRegistry> djbRegistries = registryMapper.selectDjbRegistryList(check);
        if(!djbRegistries.isEmpty()){
            JSONObject ret = new JSONObject();
            ret.put("id",djbRegistries.get(0).getId());
            return AjaxResult.error("该访客信息已登记",ret);
        }
        DjbDistrict djbDistrict = districtMapper.selectDjbDistrictById(admin.getDistrictId());
        if(userType==USER_TYPE_PERSON&&djbDistrict.getVipCheckId()==SYS_YES&&djbDistrict.getBalance()>10&&djbDistrict.getIdNumberSwitch()==SYS_YES&&idNumber!=null&&!idNumber.isEmpty()){
            boolean b = checkNameAndIdNumber(name, idNumber,djbDistrict);
            if(!b){
                return error("身份信息校验不符！");
            }
        }
        DjbRegistry registry = new DjbRegistry();
        registry.setUserId(admin.getId());
        registry.setName(name);
        registry.setMobile(mobile);
        registry.setAddress(address);
        registry.setUserType(userType);
        registry.setDistrictId(admin.getDistrictId());
        registry.setBuilding(building);

        if(djbDistrict.getType()==BUILDING_TYPE_BUILD){
            registry.setUnit(unit);
            registry.setFloor(floor);
            registry.setRoom(room);
        }else if(djbDistrict.getType()==BUILDING_TYPE_DEPARTMENT){

        }else if(djbDistrict.getType()==BUILDING_TYPE_COMPANY){

        }
        registry.setDepartment(department);
        registry.setIdNumber(idNumber);
        registry.setRemark(remark);
        String gateName="无";
        if(admin.getType().equals(ADMIN_TYPE_GATE)){
            registry.setGateId(admin.getGateId());
            DjbGate gate = gateMapper.selectDjbGateById(admin.getGateId());
            if(gate!=null){
                gateName=gate.getName();
            }
        }else{
            registry.setGateId(0);
        }
        registry.setReason(reason);
        registry.setType(type);
        registry.setStatus(SYS_NO);
        if(admin.getType().equals(ADMIN_TYPE_GATE)){
            registry.setCreateType(CREATE_TYPE_GATE);
        }else{
            registry.setCreateType(CREATE_TYPE_ADMIN);
        }
        registry.setCreateTime(DateUtils.getNowDate());
        registry.setCreateName(admin.getName());
        registry.setDistrictName(djbDistrict.getName());
        registry.setGateName(gateName);
        registry.setDistrictImage(djbDistrict.getCoverUrl());
        registry.setDistrictPhone(djbDistrict.getMobile());
        registry.setVisitPerson(visitPerson);
        registry.setVisitPersonId(visitPersonId);
        registryMapper.insertDjbRegistry(registry);
        if(djbDistrict.getType()==BUILDING_TYPE_DEPARTMENT && building!=null&& building!=0){
            DjbBuilding djbBuilding = buildingMapper.selectDjbBuildingById(building);
            djbBuilding.setVisit(djbBuilding.getVisit()+1);
            buildingMapper.updateDjbBuilding(djbBuilding);
        }
        JSONObject ret = new JSONObject();
        ret.put("registry",registry);
        return AjaxResult.success("登记成功",ret);
    }

    /*登记标记*/
    @PutMapping("/registryTag")
    @ResponseBody
    @AdminLoginToken
    public AjaxResult registryTag(HttpServletRequest request,Integer id,String content,String images,Integer sendNotice,Integer isLimit){
        DjbAdmin admin = (DjbAdmin) request.getAttribute("admin");
        DjbRelease release = releaseMapper.selectDjbReleaseById(id);
        if(release==null){
            return error("放行记录不存在");
        }
        DjbTag tag = new DjbTag();
        if(release.getUserType()==USER_TYPE_PERSON){
            tag.setMobile(release.getMobile());
        }else{
            tag.setCar(release.getName());
        }
        tag.setTag(content);
        tag.setDistrictId(admin.getDistrictId());
        tag.setCreateTime(DateUtils.getNowDate());
        if(release.getCreateType().equals(CREATE_TYPE_VISITOR)){
            tag.setUserId(release.getUserId());
        }
        tagMapper.insertDjbTag(tag);
        release.setTag(content);
        String[] split = images.split(",");
        StringBuilder imageUrl= new StringBuilder();
        for(String tmp : split){
            if(tmp.isEmpty())continue;
            imageUrl.append("http://txeimg.llmmwl.com/districtCover/").append(tmp).append(",");
        }
        String s = imageUrl.toString();
        if(!s.isEmpty()){
            s=s.substring(0,s.length()-1);
        }
        release.setImages(s);
        releaseMapper.updateDjbRelease(release);
        if(isLimit==1){
            DjbUserLimit userLimit = new DjbUserLimit();
            userLimit.setUserId(release.getUserId());
            userLimit.setDistrictId(admin.getDistrictId());
            userLimit.setCreateTime(DateUtils.getNowDate());
            userLimit.setExpireTime(DateUtils.addDays(userLimit.getCreateTime(),30));
            userLimitMapper.insertDjbUserLimit(userLimit);
        }
//        if(sendNotice==1){
//
//        }
        new Thread(() -> {
            /*发送消息通知*/
            if(release.getCreateType().equals(CREATE_TYPE_VISITOR)){
                //访客登记的由访客接收
                Integer userId = release.getUserId();
                DjbUser djbUser = userMapper.selectDjbUserById(userId);
                if(djbUser!=null&&djbUser.getOpenId2()!=null&&!djbUser.getOpenId2().isEmpty()){
                    sendTagNotice(djbUser.getOpenId2(),release.getName(),release.getMobile(),admin.getDistrictName(),content,release.getId());
                }
            }else{
                //住户登记、内部登记由登记号码最可能的微信接受
                //查找该登记号码的访客登记微信并筛选出登记次数最多的微信以此作为最有可能的微信
                JSONObject tags=new JSONObject();
                DjbRelease release2 = new DjbRelease();
                if(release.getUserType()==USER_TYPE_PERSON){
                    release2.setMobile(release.getMobile());
                }else{
                    release2.setName(release.getName());
                }
                release2.setUserType(release.getUserType());
                Map<Integer, Integer> idCountMap = new HashMap<>();
                List<DjbRelease> djbReleaseList1 = releaseMapper.selectHalfYearThreeTimeReleaseList(release2);
                for(DjbRelease tmp2: djbReleaseList1){
                    if(tmp2.getCreateType()==CREATE_TYPE_ADMIN||tmp2.getCreateType()==CREATE_TYPE_GATE) continue;
                    int userId=tmp2.getUserId();
                    idCountMap.put(userId, idCountMap.getOrDefault(userId, 0) + 1);
                }
                Integer mostFrequentID = null;
                int maxCount = 0;
                for (Map.Entry<Integer, Integer> entry : idCountMap.entrySet()) {
                    if (entry.getValue() > maxCount) {
                        mostFrequentID = entry.getKey();
                        maxCount = entry.getValue();
                    }
                }
                if(mostFrequentID!=null){
                    DjbUser djbUser = userMapper.selectDjbUserById(mostFrequentID);
                    sendTagNotice(djbUser.getOpenId2(),release.getName(),release.getMobile(),admin.getDistrictName(),content,release.getId());
                }
            }
        }).start();
        return AjaxResult.success("标记成功");
    }

    /*登记作废*/
    @PutMapping("/registryExpired")
    @ResponseBody
    @AdminLoginToken
    public AjaxResult registryExpired(HttpServletRequest request,String ids){
        DjbAdmin admin = (DjbAdmin) request.getAttribute("admin");
        String[] split = ids.split(",");
        for(String tmp : split){
            DjbRegistry registry = registryMapper.selectDjbRegistryById(Integer.parseInt(tmp));
            if(registry!=null){
                registry.setStatus(SYS_STATUS_WASTE);
                registryMapper.updateDjbRegistry(registry);
            }
        }
        return AjaxResult.success("成功");
    }

    /*登记驳回列表* */
    @GetMapping("/rebutRegistryList")
    @ResponseBody
    @AdminLoginToken
    public AjaxResult rebutRegistryList(HttpServletRequest request){
        DjbAdmin admin = (DjbAdmin) request.getAttribute("admin");
        DjbRegistry registry = new DjbRegistry();
        registry.setUserId(admin.getId());
        registry.setStatus(SYS_STATUS_REBUT);
        if(admin.getType().equals(ADMIN_TYPE_GATE)){
            registry.setCreateType(CREATE_TYPE_GATE);
        }else{
            registry.setCreateType(CREATE_TYPE_ADMIN);
        }
        List<DjbRegistry> djbRegistries = registryMapper.selectDjbRegistryList(registry);
        if(djbRegistries.size()==0){
            return AjaxResult.warn("暂无登记驳回列表");
        }
        Map<String,Object> ret = new HashMap<>();
        ret.put("rebutRegistryList",djbRegistries);
        return success(ret);
    }

    /*切换门岗*/
    @PutMapping("/adminChangeGate")
    @ResponseBody
    @AdminLoginToken
    public AjaxResult adminChangeGate(HttpServletRequest request,Integer id){
        DjbAdmin admin = (DjbAdmin) request.getAttribute("admin");
        DjbGate djbGate = gateMapper.selectDjbGateById(id);
        if(djbGate==null){
            return error("门岗不存在");
        }
        /*如果门卫切换门岗时是上岗状态，则要把目标门岗之前的上岗门卫置为离岗*/
        /*只要上岗，三人平级*/
//        if(admin.getIsPost()==SYS_YES){
//            DjbAdmin query = new DjbAdmin();
//            query.setGateId(id);
//            List<DjbAdmin> djbAdmins = adminMapper.selectDjbAdminList(query);
//            for(DjbAdmin tmp : djbAdmins){
//                tmp.setIsPost(SYS_NO);
//                adminMapper.updateDjbAdmin(tmp);
//            }
//        }
        admin.setGateName(djbGate.getName());
        admin.setGateId(id);
        adminMapper.updateDjbAdmin(admin);
        JSONObject ret = new JSONObject();
        ret.put("admin",admin);
        return AjaxResult.success("切换成功",ret);
    }

    /*切换上下岗*/
    @PutMapping("/adminChangeStatus")
    @ResponseBody
    @AdminLoginToken
    public AjaxResult adminChangeStatus(HttpServletRequest request,Integer isPost){
        DjbAdmin admin = (DjbAdmin) request.getAttribute("admin");
        /*如果门卫切换上岗状态，则要把当前门岗的上岗门卫置为离岗*/
        /*只要上岗，三人平级*/
//        if(isPost==SYS_YES){
//            DjbAdmin query = new DjbAdmin();
//            query.setGateId(admin.getGateId());
//            List<DjbAdmin> djbAdmins = adminMapper.selectDjbAdminList(query);
//            for(DjbAdmin tmp : djbAdmins){
//                if(tmp.getId().equals(admin.getId())) continue;
//                tmp.setIsPost(SYS_NO);
//                adminMapper.updateDjbAdmin(tmp);
//            }
//        }
        admin.setIsPost(isPost);
        adminMapper.updateDjbAdmin(admin);
        JSONObject ret = new JSONObject();
        ret.put("admin",admin);
        return AjaxResult.success("查询成功",ret);
    }

    /*门卫绑定门岗列表*/
    @GetMapping("/adminBindgate")
    @ResponseBody
    @AdminLoginToken
    public AjaxResult adminBindgate(HttpServletRequest request,String imageName){
        DjbAdmin admin = (DjbAdmin) request.getAttribute("admin");
        DjbGate djbGate = new DjbGate();
        djbGate.setKeeper("\"id\":\""+admin.getId()+"\"");
        djbGate.setDistrictId(admin.getDistrictId());
        List<DjbGate> djbGates = gateMapper.selectDjbGateList(djbGate);
        if(djbGates.isEmpty()){
            return AjaxResult.warn("没有绑定的门岗");
        }
        JSONObject ret = new JSONObject();
        ret.put("gateList",djbGates);
        return success(ret);
    }

    /*更换头像*/
    @GetMapping("/adminUserUpdateHeadImg")
    @ResponseBody
    @AdminLoginToken
    public AjaxResult adminUserUpdateHeadImg(HttpServletRequest request,String imageName){
        DjbAdmin admin = (DjbAdmin) request.getAttribute("admin");
        String imageUrl = "http://txeimg.llmmwl.com/districtCover/"+imageName;
        admin.setHeadUrl(imageUrl);
        adminMapper.updateDjbAdmin(admin);
        JSONObject ret = new JSONObject();
        ret.put("admin",admin);
        return AjaxResult.success("修改成功",ret);
    }

    /*小区解散*/
    @GetMapping("/districtInfoDelete")
    @ResponseBody
    @AdminLoginToken
    public AjaxResult districtInfoDelete(HttpServletRequest request,Integer id){
        if(id==null){
            return error("严重错误！严重错误！严重错误！");
        }
        if(env.equals("PROD")){
            return error("正式环境不能解散！");
        }
        DjbAdmin admin = (DjbAdmin) request.getAttribute("admin");
        districtMapper.deleteDjbDistrictById(id);
        /*删除住户信息*/
        DjbDistrictUser districtUser = new DjbDistrictUser();
        districtUser.setDistrictId(id);
        List<DjbDistrictUser> djbDistrictUsers = districtUserMapper.selectDjbDistrictUserList(districtUser);
        for(DjbDistrictUser tmp : djbDistrictUsers){
            districtUserMapper.deleteDjbDistrictUserById(tmp.getId());
        }
        /*解绑员工*/
        DjbAdmin admin1 = new DjbAdmin();
        admin1.setDistrictId(id);
        List<DjbAdmin> djbAdmins = adminMapper.selectDjbAdminList(admin1);
        for(DjbAdmin tmp : djbAdmins){
            String districtName = tmp.getDistrictName();
            tmp.setDistrictId(0);
            tmp.setDistrictName("");
            tmp.setType(ADMIN_TYPE_NONE);
            tmp.setStatus(SYS_STATUS_TODO);
            tmp.setGateId(0);
            tmp.setGateName("");
            tmp.setIsPost(SYS_NO);
            tmp.setReason("");
            tmp.setRemark(SYS_STATUS_DISSOLUTION+":"+districtName);
            adminMapper.updateDjbAdmin(tmp);
        }
        /*清理门岗和楼座*/
        DjbBuilding building = new DjbBuilding();
        building.setDistrictId(id);
        List<DjbBuilding> djbBuildings = buildingMapper.selectDjbBuildingList(building);
        for(DjbBuilding tmp: djbBuildings){
            buildingMapper.deleteDjbBuildingById(tmp.getId());
        }
        DjbGate djbGate = new DjbGate();
        djbGate.setDistrictId(id);
        List<DjbGate> djbGates = gateMapper.selectDjbGateList(djbGate);
        for(DjbGate tmp : djbGates){
            gateMapper.deleteDjbGateById(tmp.getId());
        }
        /*清理登记和放行列表*/
        DjbRegistry registry = new DjbRegistry();
        registry.setDistrictId(id);
        List<DjbRegistry> djbRegistries = registryMapper.selectDjbRegistryList(registry);
        for(DjbRegistry tmp : djbRegistries){
            registryMapper.deleteDjbRegistryById(tmp.getId());
        }
        DjbRelease release = new DjbRelease();
        release.setDistrictId(id);
        List<DjbRelease> djbReleaseList = releaseMapper.selectDjbReleaseList(release);
        for(DjbRelease tmp : djbReleaseList){
            releaseMapper.deleteDjbReleaseById(tmp.getId());
        }
        return AjaxResult.success("解散成功");
    }

    /*小区信息编辑*/
    @PutMapping("/districtInfoUpdate")
    @ResponseBody
    @AdminLoginToken
    public AjaxResult districtInfoUpdate(HttpServletRequest request,String province,String notice,Integer id,String name,String address,String mobile,String longitude,String latitude,String coverUrl){
        DjbAdmin admin = (DjbAdmin) request.getAttribute("admin");
        if(admin==null||admin.getDistrictId()==null){
            return error("信息获取失败");
        }
        DjbDistrict update = districtMapper.selectDjbDistrictById(admin.getDistrictId());
        if(update==null){
            return error("机构不存在");
        }
        String oldName=update.getName();
        update.setName(name);
        update.setAddress(address);
        update.setLongitude(longitude);
        update.setLatitude(latitude);
        update.setMobile(mobile);
        update.setNotice(notice);
        update.setProvince(province);
        if(!coverUrl.contains("http")){
            String imageUrl = "http://txeimg.llmmwl.com/districtCover/"+coverUrl;
            update.setCoverUrl(imageUrl);
        }
        districtMapper.updateDjbDistrict(update);
        /*如果修改了小区名称，联动修改住户的楼座名称、修改*/
        if(!name.isEmpty()&&!name.equals(oldName)){
            DjbDistrictUser query = new DjbDistrictUser();
            query.setDistrictId(id);
            List<DjbDistrictUser> djbDistrictUsers = districtUserMapper.selectDjbDistrictUserList(query);
            for(DjbDistrictUser tmp : djbDistrictUsers){
                tmp.setDistrictName(name);
                districtUserMapper.updateDjbDistrictUser(tmp);
            }

            DjbAdmin admin1 = new DjbAdmin();
            admin1.setDistrictId(id);
            List<DjbAdmin> djbAdmins = adminMapper.selectDjbAdminList(admin1);
            for(DjbAdmin tmp : djbAdmins){
                tmp.setDistrictName(name);
                adminMapper.updateDjbAdmin(tmp);
            }
        }
        return AjaxResult.success("修改成功");
    }

    /*访客登记管理*/
    @PutMapping("/visitorRegistryManage")
    @ResponseBody
    @AdminLoginToken
    public AjaxResult visitorRegistryManage(HttpServletRequest request,int manualReview,int conditons,int  noReviewTime){
        DjbAdmin admin = (DjbAdmin) request.getAttribute("admin");
        if(admin==null||admin.getDistrictId()==null){
            return error("小区信息获取失败");
        }
        DjbDistrict update = districtMapper.selectDjbDistrictById(admin.getDistrictId());
        if(update==null){
            return error("小区不存在");
        }
        update.setManualReview(manualReview);
        update.setConditons(conditons);
        update.setNoReviewTime(noReviewTime);
        districtMapper.updateDjbDistrict(update);
        return AjaxResult.success("修改成功");
    }

    /*业主登记管理*/
    @PutMapping("/userRegistryManage")
    @ResponseBody
    @AdminLoginToken
    public AjaxResult userRegistryManage(HttpServletRequest request,int manualReview,int conditons,int  noReviewTime,int  nightScene,int conditionsNightScene){
        DjbAdmin admin = (DjbAdmin) request.getAttribute("admin");
        if(admin==null||admin.getDistrictId()==null){
            return error("小区信息获取失败");
        }
        DjbDistrict update = districtMapper.selectDjbDistrictById(admin.getDistrictId());
        if(update==null){
            return error("小区不存在");
        }
        update.setManualReviewUser(manualReview);
        update.setConditionsUser(conditons);
        update.setNoReviewTimeUser(noReviewTime);
        update.setNightScene(nightScene);
        update.setConditionsNightScene(conditionsNightScene);
        districtMapper.updateDjbDistrict(update);
        return AjaxResult.success("修改成功");
    }

    /*小区信息创建*/
    @PostMapping("/districtInfoAdd")
    @ResponseBody
    @AdminLoginToken
    public AjaxResult districtInfoAdd(HttpServletRequest request,String province,String notice,String adminName,String adminMobile,String name,String address,String mobile,String longitude,String latitude,String coverUrl,String vCode,Integer type){
        if(vCode!=null && !vCode.isEmpty()){
            /*校验验证码*/
            if(!checkPhoneCode(adminMobile,Integer.parseInt(vCode))){
                return AjaxResult.error("手机验证码错误");
            }
        }
        if(type==null){
            type=1;
        }
        DjbAdmin admin = (DjbAdmin) request.getAttribute("admin");
        DjbDistrict add = new DjbDistrict();
        add.setName(name);
        add.setAddress(address);
        add.setMobile(mobile);
        add.setLongitude(longitude);
        add.setLatitude(latitude);
        add.setNotice(notice);
        add.setProvince(province);
        add.setType(type);
        if(coverUrl.isEmpty()){
            add.setCoverUrl("http://txeimg.llmmwl.com/districtCover/defaultDistrictCoverImg.png");
        }else{
            String imageUrl = "http://txeimg.llmmwl.com/districtCover/"+coverUrl;
            add.setCoverUrl(imageUrl);
        }
        add.setStatus(SYS_STATUS_PASS);
        add.setVipIncomeSmsWord("您好（鲁B****3），欢迎来到******，来访期间请杜绝乱停车等违规行为，谢谢。");
        add.setVipOutSmsWord("您好（鲁B****3），您的本次来访******时间已到，请尽快离场，如已离场，请勿理会。");
        districtMapper.insertDjbDistrict(add);
        Integer id = add.getId();

        initDjbReason(id,type);

        admin.setDistrictId(id);
        admin.setDistrictName(add.getName());
        admin.setName(adminName);
        admin.setMobile(adminMobile);
        admin.setType(ADMIN_TYPE_ADMIN);
        admin.setStatus(SYS_STATUS_PASS);
        adminMapper.updateDjbAdmin(admin);
        JSONObject ret = new JSONObject();
        ret.put("admin",admin);
        ret.put("districtDetail",add);
        return AjaxResult.success("新建成功",ret);
    }

    /*检查更新*/
    @GetMapping("/checkUpdate")
    @ResponseBody
    @PassToken
    public  AjaxResult checkUpdate(String plat,Integer versionCode){
        DjbVersion djbVersion = new DjbVersion();
        djbVersion.setPlatform(plat);
        djbVersion=versionMapper.selectDjbVersionList(djbVersion).get(0);
        if(djbVersion.getVersionCode()>versionCode){
            return AjaxResult.warn("需要更新",djbVersion);
        }
        return AjaxResult.success("当前已是最新版本",djbVersion);
    }

    /*住户列表*/
    @GetMapping("/districtUserList")
    @ResponseBody
    @AdminLoginToken
    public AjaxResult districtUserList(HttpServletRequest request){
        DjbAdmin admin = (DjbAdmin) request.getAttribute("admin");
        DjbDistrictUser query = new DjbDistrictUser();
        query.setDistrictId(admin.getDistrictId());
        List<DjbDistrictUser> djbDistrictUsers = districtUserMapper.selectDjbDistrictUserList(query);
        if(djbDistrictUsers.isEmpty()){
            return AjaxResult.warn("暂无数据");
        }
        JSONObject ret = new JSONObject();
        ret.put("districtUserList",djbDistrictUsers);
        return AjaxResult.success("查询成功",ret);
    }

    /*住户信息编辑*/
    @PutMapping("/districtUserUpdate")
    @ResponseBody
    @AdminLoginToken
    public AjaxResult districtUserUpdate(HttpServletRequest request,Integer id,Integer type,Integer building,Integer unit,Integer floor,Integer room, String mobile, String name){
        DjbAdmin admin = (DjbAdmin) request.getAttribute("admin");
        DjbDistrictUser update = districtUserMapper.selectDjbDistrictUserById(id);
        update.setName(name);
        update.setMobile(mobile);
        update.setBuilding(building);
        update.setType(type);
        DjbDistrict djbDistrict = districtMapper.selectDjbDistrictById(admin.getDistrictId());
        DjbBuilding djbBuilding = buildingMapper.selectDjbBuildingById(building);
        if(djbDistrict.getType()==BUILDING_TYPE_BUILD){
            update.setUnit(unit);
            update.setFloor(floor);
            update.setRoom(room);
            update.setAddress(djbBuilding.getName()+(unit==0?"":unit+"单元")+floor+String.format("%02d",room));
        }else if(djbDistrict.getType()==BUILDING_TYPE_DEPARTMENT||djbDistrict.getType()==BUILDING_TYPE_COMPANY){
            update.setAddress(djbBuilding.getName());
        }
        districtUserMapper.updateDjbDistrictUser(update);
        return AjaxResult.success("修改成功");
    }

    /*住户认证新增*/
    @PutMapping("/districtUserAdd")
    @ResponseBody
    @AdminLoginToken
    public AjaxResult districtUserAdd(HttpServletRequest request,Integer type,Integer building,Integer unit,Integer floor,Integer room, String mobile, String name){
        DjbAdmin admin = (DjbAdmin) request.getAttribute("admin");
        DjbDistrictUser add = new DjbDistrictUser();
        add.setUserId(null);
        add.setDistrictId(admin.getDistrictId());
        DjbDistrict djbDistrict = districtMapper.selectDjbDistrictById(admin.getDistrictId());
        add.setDistrictName(admin.getDistrictName());
        add.setStatus(SYS_STATUS_TODO);
        add.setName(name);
        add.setMobile(mobile);
        add.setBuilding(building);
        DjbBuilding djbBuilding = buildingMapper.selectDjbBuildingById(building);
        String address="";
        if(djbDistrict.getType()==BUILDING_TYPE_BUILD){
            add.setUnit(unit);
            add.setFloor(floor);
            add.setRoom(room);
            add.setHead("");
            address=djbBuilding.getName()+(unit==0?"":unit+"单元")+floor+String.format("%02d",room);
        }else if(djbDistrict.getType()==BUILDING_TYPE_DEPARTMENT){
            address=djbBuilding.getName();
        }else if(djbDistrict.getType()==BUILDING_TYPE_COMPANY){
            address=djbBuilding.getName();
        }
        add.setAddress(address);
        add.setType(type);
        add.setAuthentication(0);

        districtUserMapper.insertDjbDistrictUser(add);
        JSONObject ret = new JSONObject();
        ret.put("id",add.getId());
        return AjaxResult.success("成功",ret);
    }

    /*住户信息删除*/
    @DeleteMapping("/districtUserDelete")
    @ResponseBody
    @AdminLoginToken
    public AjaxResult districtUserDelete(HttpServletRequest request,Integer id){
        DjbAdmin admin = (DjbAdmin) request.getAttribute("admin");
        districtUserMapper.deleteDjbDistrictUserById(id);
        return AjaxResult.success("刪除成功");
    }

    /*住户信息审核*/
    @PutMapping("/districtUserVerify")
    @ResponseBody
    @AdminLoginToken
    public AjaxResult districtUserVerify(HttpServletRequest request,Integer id,Integer status,String reason){
        DjbAdmin admin = (DjbAdmin) request.getAttribute("admin");
        DjbDistrictUser districtUser = districtUserMapper.selectDjbDistrictUserById(id);
        if(!districtUser.getStatus().equals(SYS_STATUS_TODO)&&(!districtUser.getStatus().equals(status))){
            return error("住户状态已改变，请返回刷新重试");
        }
        districtUser.setStatus(status);
        if(status==SYS_STATUS_REJECT){
            districtUser.setRemark(reason);
        }
        districtUserMapper.updateDjbDistrictUser(districtUser);
        DjbDistrict djbDistrict = districtMapper.selectDjbDistrictById(admin.getDistrictId());
        String name="";
        if(djbDistrict.getType()==BUILDING_TYPE_BUILD){
            if(districtUser.getType()==1){
                name="户主";
            }else{
                name="非户主";
            }
        }else if(djbDistrict.getType()==BUILDING_TYPE_DEPARTMENT){
            if(districtUser.getType()==1){
                name="主管";
            }else{
                name="非主管";
            }
        }else if(djbDistrict.getType()==BUILDING_TYPE_COMPANY){
            if(districtUser.getType()==1){
                name="前台";
            }else{
                name="成员";
            }
        }
        //找业主
        DjbDistrictUser check = new DjbDistrictUser();
        check.setDistrictId(districtUser.getDistrictId());
        check.setBuilding(districtUser.getBuilding());

        if(djbDistrict.getType()==BUILDING_TYPE_BUILD){
            check.setUnit(districtUser.getUnit());
            check.setFloor(districtUser.getFloor());
            check.setRoom(districtUser.getRoom());
        }
        List<DjbDistrictUser> djbDistrictUsers = districtUserMapper.selectDjbDistrictUserList(check);
        for(DjbDistrictUser tmp: djbDistrictUsers){
            if(tmp.getType().equals(0)) continue;
            DjbUser djbUser = userMapper.selectDjbUserById(tmp.getUserId());
            if(djbUser ==null) continue;
            /*消息改为关注公众号是模板消息，如果没有关注公众号直接用小程序订阅消息接受*/
            if(djbUser.getOpenId2()!=null&&!djbUser.getOpenId2().isEmpty()){
                /*关注了公众号*/
                sendExamNotice3(djbUser.getOpenId2(), districtUser.getName(),districtUser.getMobile(), name, districtUser.getAddress(), districtUser.getId(),status==SYS_STATUS_REJECT?"不通过（认证信息有误）":"通过");
            }else {
                /*发送小程序订阅通知*/
                sendUserVerifyResult(djbUser.getOpenId(),districtUser.getName(),districtUser.getMobile(),districtUser.getAddress(),name);
            }
        }
        /*给申请人自己 发送身份认证审核结果通知*/
        if(districtUser.getType()==0){
            DjbUser djbUser = userMapper.selectDjbUserById(districtUser.getUserId());
            if((djbUser.getOpenId2()!=null) && !djbUser.getOpenId2().isEmpty()){
                sendExamNotice3(djbUser.getOpenId2(), districtUser.getName(),districtUser.getMobile(), name, districtUser.getAddress(), districtUser.getId(),status==SYS_STATUS_REJECT?"不通过（认证信息有误）":"通过");
            }else {
                /*发送小程序订阅通知*/
                sendUserVerifyResult(djbUser.getOpenId(),districtUser.getName(),districtUser.getMobile(),districtUser.getAddress(),name);
            }
        }
        return AjaxResult.success("审核成功");
    }

    /*小区列表* */
    @GetMapping("/districtList")
    @ResponseBody
    @AdminLoginToken
    public AjaxResult districtList(HttpServletRequest request,String longitude,String latitude){
        DjbAdmin admin = (DjbAdmin) request.getAttribute("admin");
        List<DjbDistrict> djbDistricts = districtMapper.selectDjbDistrictList(new DjbDistrict());
        for(DjbDistrict tmp : djbDistricts){
            double distance = getDistance(Double.parseDouble(tmp.getLongitude()), Double.parseDouble(tmp.getLatitude()), Double.parseDouble(longitude), Double.parseDouble(latitude));
            tmp.setDistance((int) distance);
        }
        djbDistricts.sort((o1, o2) -> {
            Integer name1 = o1.getDistance();//name1是从你list里面拿出来的一个
            Integer name2 = o2.getDistance();//name1是从你list里面拿出来的一个
            return name1.compareTo(name2);
        });
        Map<String,Object> ret = new HashMap<>();
        ret.put("districtList",djbDistricts);
        return success(ret);
    }

    /*员工加入审核*/
    @PutMapping("/adminUserAddVerify")
    @ResponseBody
    @AdminLoginToken
    private AjaxResult adminUserAddVerify(HttpServletRequest request,String name,String mobile,Integer districtId,Integer type){
        DjbAdmin check = new DjbAdmin();
        check.setMobile(mobile);
        List<DjbAdmin> djbAdmins = adminMapper.selectDjbAdminList(check);
        if(!djbAdmins.isEmpty()){
            return error("该手机号已存在");
        }
        DjbAdmin add = (DjbAdmin) request.getAttribute("admin");
        DjbDistrict djbDistrict = districtMapper.selectDjbDistrictById(districtId);
        add.setDistrictId(districtId);
        add.setDistrictName(djbDistrict.getName());
        add.setName(name);
        add.setMobile(mobile);
        add.setType(type);
        add.setStatus(SYS_STATUS_TODO);
        adminMapper.updateDjbAdmin(add);
        return AjaxResult.success("加入成功，审核中");
    }

    /*员工取消审核*/
    @DeleteMapping("/adminUserDeleteVerify")
    @ResponseBody
    @AdminLoginToken
    public AjaxResult adminUserDeleteVerify(HttpServletRequest request){
        DjbAdmin add = (DjbAdmin) request.getAttribute("admin");
        if(add.getStatus().equals(SYS_STATUS_PASS)){
            return error("审核通过，无法取消");
        }
        add.setDistrictId(0);
        add.setDistrictName("");
        add.setName("");
        add.setMobile("");
        add.setType(ADMIN_TYPE_NONE);
        add.setStatus(SYS_NO);
        adminMapper.updateDjbAdmin(add);
        return AjaxResult.success("取消审核成功");
    }

    /*员工列表*/
    @GetMapping("/adminUserList")
    @ResponseBody
    @AdminLoginToken
    public AjaxResult adminUserList(HttpServletRequest request){
        DjbAdmin admin = (DjbAdmin) request.getAttribute("admin");
        DjbAdmin query = new DjbAdmin();
        query.setDistrictId(admin.getDistrictId());
        List<DjbAdmin> djbAdmins = adminMapper.selectDjbAdminList(query);
        if(djbAdmins.isEmpty()){
            return AjaxResult.warn("无记录",djbAdmins);
        }
        JSONObject ret = new JSONObject();
        ret.put("adminUserList",djbAdmins);
        return AjaxResult.success("查询成功",ret);
    }

    /*员工信息编辑*/
    @PutMapping("/adminUserUpdate")
    @ResponseBody
    @AdminLoginToken
    public AjaxResult adminUserUpdate(HttpServletRequest request,Integer id,String name,String mobile,Integer type){
        DjbAdmin admin = (DjbAdmin) request.getAttribute("admin");
        DjbAdmin update = adminMapper.selectDjbAdminById(id);
        DjbAdmin check = new DjbAdmin();
        check.setDistrictId(admin.getDistrictId());
        check.setType(ADMIN_TYPE_ADMIN);
        List<DjbAdmin> djbAdmins = adminMapper.selectDjbAdminList(check);
        if(djbAdmins.size()==1&& admin.getId().equals(id)){
            return error("您是唯一管理员\n无法修改职务");
        }
        if(update.getType()==ADMIN_TYPE_GATE&& !type.equals(update.getType())){
            //解绑门卫
            update.setGateId(0);
            update.setIsPost(0);
            update.setGateName("");
            DjbGate djbGate = new DjbGate();
            djbGate.setKeeper("\"id\":\""+update.getId()+"\"");
            djbGate.setDistrictId(admin.getDistrictId());
            List<DjbGate> djbGates = gateMapper.selectDjbGateList(djbGate);
            for(DjbGate tmp: djbGates){
                JSONArray array = JSONArray.parseArray(tmp.getKeeper());
                for(int i=0;i<array.size();i++){
                    JSONObject o = array.getJSONObject(i);
                    if(o.getInteger("id").equals(update.getId())){
                        array.remove(i);
                        break;
                    }
                }
                tmp.setKeeper(array.toJSONString());
                gateMapper.updateDjbGate(tmp);
            }
        }else if(update.getType()==ADMIN_TYPE_WUYE&& !type.equals(update.getType())){
            //解绑管家
            DjbBuilding djbBuilding = new DjbBuilding();
            djbBuilding.setKeeper("\"id\":\""+update.getId()+"\"");
            List<DjbBuilding> djbBuildings = buildingMapper.selectDjbBuildingList(djbBuilding);
            for(DjbBuilding building : djbBuildings){
                JSONArray array = JSONArray.parseArray(building.getKeeper());
                for(int i=0;i<array.size();i++){
                    JSONObject o = array.getJSONObject(i);
                    if(o.getInteger("id").equals(update.getId())){
                        array.remove(i);
                        break;
                    }
                }
                building.setKeeper(array.toJSONString());
                buildingMapper.updateDjbBuilding(building);
            }
        }
        update.setName(name);
        update.setMobile(mobile);
        update.setType(type);
        adminMapper.updateDjbAdmin(update);
        return AjaxResult.success("编辑成功");
    }

    /*员工信息删除*/
    @DeleteMapping("/adminUserDelete")
    @ResponseBody
    @AdminLoginToken
    public AjaxResult adminUserDelete(HttpServletRequest request,Integer id){
        DjbAdmin admin = (DjbAdmin) request.getAttribute("admin");
        DjbAdmin check = new DjbAdmin();
        check.setDistrictId(admin.getDistrictId());
        check.setType(ADMIN_TYPE_ADMIN);
        List<DjbAdmin> djbAdmins = adminMapper.selectDjbAdminList(check);
        if(djbAdmins.size()==1&& admin.getId().equals(id)){
            return error("您是唯一管理员\n无法删除");
        }
        DjbAdmin delete = adminMapper.selectDjbAdminById(id);

        /*如果是管家，删除后解除楼座绑定*/
        if(delete.getType().equals(ADMIN_TYPE_WUYE)){
            /*显示自己已绑定的楼座*/
            List<Integer> integers = queryBuilding2(delete.getId());
            for(Integer buildingId : integers){
                DjbBuilding building = buildingMapper.selectDjbBuildingById(buildingId);
                String keeper = building.getKeeper();
                JSONArray array = JSONArray.parseArray(keeper);
                for(int i =0;i<array.size();i++){
                    JSONObject jsonObject = array.getJSONObject(i);
                    if(jsonObject.getIntValue("id")==delete.getId()){
                        array.remove(i);
                        break;
                    }
                }
                building.setKeeper(array.toJSONString());
                buildingMapper.updateDjbBuilding(building);
            }
        }
        String districtName = delete.getDistrictName();
        delete.setDistrictId(0);
        delete.setMobile("");
        delete.setDistrictName("");
        delete.setType(ADMIN_TYPE_NONE);
        delete.setStatus(SYS_STATUS_TODO);
        delete.setGateId(0);
        delete.setGateName("");
        delete.setIsPost(SYS_NO);
        delete.setReason("");
        delete.setRemark(SYS_STATUS_DELETE+":"+districtName);
        adminMapper.updateDjbAdmin(delete);
        return AjaxResult.success("删除成功");
    }

    /*员工信息审核*/
    @PutMapping("/adminUserVerify")
    @ResponseBody
    @AdminLoginToken
    public AjaxResult adminUserVerify(HttpServletRequest request,Integer id,Integer status,String reason,Integer type){
        DjbAdmin admin = (DjbAdmin) request.getAttribute("admin");
        DjbAdmin verify = adminMapper.selectDjbAdminById(id);
        verify.setStatus(status);
        verify.setType(type);
        if(status==SYS_STATUS_REJECT){
            verify.setReason(reason);
        }else{
            verify.setDistrictName(admin.getDistrictName());
        }
        adminMapper.updateDjbAdmin(verify);
        return AjaxResult.success("审核成功");
    }

    /*门岗列表*/
    @GetMapping("/gateList")
    @ResponseBody
    @AdminLoginToken
    public AjaxResult gateList(HttpServletRequest request){
        DjbAdmin admin = (DjbAdmin) request.getAttribute("admin");
        DjbGate query = new DjbGate();
        query.setDistrictId(admin.getDistrictId());
        List<DjbGate> djbGates = gateMapper.selectDjbGateList(query);
        if(djbGates.isEmpty()){
            return AjaxResult.warn("无记录",djbGates);
        }
        for(DjbGate tmp : djbGates){
            if(tmp.getBluetoothIn()!=0){
                DjbDistrictBluetooth djbDistrictBluetooth = bluetoothMapper.selectDjbDistrictBluetoothById(tmp.getBluetoothIn());
                tmp.setBluetoothInName(djbDistrictBluetooth.getName());
                tmp.setBluetoothInMac(djbDistrictBluetooth.getMac());
            }else{
                tmp.setBluetoothInName("");
                tmp.setBluetoothInMac("");
            }
            if(tmp.getBluetoothOut()!=0){
                DjbDistrictBluetooth djbDistrictBluetooth = bluetoothMapper.selectDjbDistrictBluetoothById(tmp.getBluetoothOut());
                tmp.setBluetoothOutName(djbDistrictBluetooth.getName());
                tmp.setBluetoothOutMac(djbDistrictBluetooth.getMac());
            }else{
                tmp.setBluetoothOutName("");
                tmp.setBluetoothOutMac("");
            }
            if(tmp.getGuardDevice()!=0){
                DjbDistrictBluetooth djbDistrictBluetooth = bluetoothMapper.selectDjbDistrictBluetoothById(tmp.getGuardDevice());
                tmp.setGuardDeviceName(djbDistrictBluetooth.getName());
                tmp.setGuardDeviceMac(djbDistrictBluetooth.getMac());
            }else{
                tmp.setGuardDeviceName("");
                tmp.setGuardDeviceMac("");
            }
        }
        JSONObject ret = new JSONObject();
        ret.put("gateList",djbGates);
        return AjaxResult.success("查询成功",ret);
    }

    /*门岗编辑*/
    @PutMapping("/gateUpdate")
    @ResponseBody
    @AdminLoginToken
    public AjaxResult gateUpdate(HttpServletRequest request,Integer id,String name,String address,String longitude,String latitude,Integer isGuard,Integer isRegiste,
                                 Integer registeBeginHour,Integer registeBeginMinute,Integer registeEndHour,Integer registeEndMinute,
                                 Integer registeType,String keeper,Integer blueToothIn,Integer blueToothOut,Integer guardDevice,String buildingIds){
        DjbAdmin admin = (DjbAdmin) request.getAttribute("admin");
        DjbGate update = gateMapper.selectDjbGateById(id);
        String oldName=update.getName();
        Integer bluetoothInOld = update.getBluetoothIn();
        Integer bluetoothOutOld = update.getBluetoothOut();
        Integer guardDeviceOld = update.getGuardDevice();
        update.setDistrictId(admin.getDistrictId());
        update.setName(name);
        update.setAddress(address);
        update.setLatitude(latitude);
        update.setLongitude(longitude);
        update.setIsGuard(isGuard);
        update.setIsRegiste(isRegiste);
        update.setBluetoothIn(blueToothIn);
        update.setBluetoothOut(blueToothOut);
        update.setGuardDevice(guardDevice);
        if(blueToothIn!=null&&blueToothIn!=0&& !blueToothIn.equals(bluetoothInOld)){
            DjbDistrictBluetooth djbDistrictBluetooth = bluetoothMapper.selectDjbDistrictBluetoothById(blueToothIn);
            djbDistrictBluetooth.setGateId(update.getId());
            djbDistrictBluetooth.setGateName(update.getName());
            djbDistrictBluetooth.setType("入场");
            bluetoothMapper.updateDjbDistrictBluetooth(djbDistrictBluetooth);
        }
        if(blueToothOut!=null&&blueToothOut!=0&& !blueToothOut.equals(bluetoothOutOld)){
            DjbDistrictBluetooth djbDistrictBluetooth = bluetoothMapper.selectDjbDistrictBluetoothById(blueToothOut);
            djbDistrictBluetooth.setGateId(update.getId());
            djbDistrictBluetooth.setGateName(update.getName());
            djbDistrictBluetooth.setType("出场");
            bluetoothMapper.updateDjbDistrictBluetooth(djbDistrictBluetooth);
        }
        if(guardDevice!=null&&guardDevice!=0&& !guardDevice.equals(guardDeviceOld)){
            DjbDistrictBluetooth djbDistrictBluetooth = bluetoothMapper.selectDjbDistrictBluetoothById(guardDevice);
            djbDistrictBluetooth.setGateId(update.getId());
            djbDistrictBluetooth.setGateName(update.getName());
            djbDistrictBluetooth.setType("门禁");
            bluetoothMapper.updateDjbDistrictBluetooth(djbDistrictBluetooth);
        }
        /*解除旧的设备*/
        if(bluetoothInOld!=0&&blueToothIn!=null&& !blueToothIn.equals(bluetoothInOld)){
            DjbDistrictBluetooth djbDistrictBluetooth = bluetoothMapper.selectDjbDistrictBluetoothById(bluetoothInOld);
            djbDistrictBluetooth.setGateId(0);
            djbDistrictBluetooth.setGateName("");
            djbDistrictBluetooth.setType("");
            bluetoothMapper.updateDjbDistrictBluetooth(djbDistrictBluetooth);
        }
        if(bluetoothOutOld!=0&&blueToothOut!=null&& !blueToothOut.equals(bluetoothOutOld)){
            DjbDistrictBluetooth djbDistrictBluetooth = bluetoothMapper.selectDjbDistrictBluetoothById(bluetoothOutOld);
            djbDistrictBluetooth.setGateId(0);
            djbDistrictBluetooth.setGateName("");
            djbDistrictBluetooth.setType("");
            bluetoothMapper.updateDjbDistrictBluetooth(djbDistrictBluetooth);
        }
        if(guardDeviceOld!=0&&guardDevice!=null&& !guardDevice.equals(guardDeviceOld)){
            DjbDistrictBluetooth djbDistrictBluetooth = bluetoothMapper.selectDjbDistrictBluetoothById(guardDeviceOld);
            djbDistrictBluetooth.setGateId(0);
            djbDistrictBluetooth.setGateName("");
            djbDistrictBluetooth.setType("");
            bluetoothMapper.updateDjbDistrictBluetooth(djbDistrictBluetooth);
        }
//        JSONArray array= new JSONArray();
//        String[] split = keeper.split(",");
//        for(String id2 : split){
//            DjbAdmin admin1 = adminMapper.selectDjbAdminById(Integer.parseInt(id2));
//            JSONObject tmp = new JSONObject();
//            tmp.put("id",id2);
//            tmp.put("name",admin1.getName());
//            array.add(tmp);
//        }
//        update.setKeeper(array.toJSONString());
        if(isRegiste==SYS_YES){
            update.setRegisteBeginHour(registeBeginHour);
            update.setRegisteBeginMinute(registeBeginMinute);
            update.setRegisteEndHour(registeEndHour);
            update.setRegisteEndMinute(registeEndMinute);
            update.setRegisteType(registeType);
        }
        List<String> buildingNames= new ArrayList<>();
        if(buildingIds!=null && !buildingIds.isEmpty()){
            String[] split = buildingIds.split(",");
            for(String tmp : split){
                DjbBuilding building = buildingMapper.selectDjbBuildingById(Integer.parseInt(tmp));
                if(building!=null){
                    buildingNames.add(building.getName());
                }
            }
            update.setBuildingIds(buildingIds);
            update.setBuildingNames(String.join(",",buildingNames));
        }else{
            update.setBuildingIds("");
            update.setBuildingNames("");
        }
        gateMapper.updateDjbGate(update);
        /*如果修改了门岗名称，联动修改门卫的门岗名称*/
        if(!name.isEmpty()&&!name.equals(oldName)){
            DjbAdmin admin1 = new DjbAdmin();
            admin1.setGateId(id);
            List<DjbAdmin> djbAdmins = adminMapper.selectDjbAdminList(admin1);
            for(DjbAdmin tmp : djbAdmins){
                tmp.setGateName(name);
                adminMapper.updateDjbAdmin(tmp);
            }
        }
        return AjaxResult.success("编辑成功");
    }

    /*门岗删除*/
    @DeleteMapping("/gateDelete")
    @ResponseBody
    @AdminLoginToken
    public AjaxResult gateDelete(HttpServletRequest request,Integer id){
        DjbAdmin admin = (DjbAdmin) request.getAttribute("admin");
        int i = gateMapper.deleteDjbGateById(id);
        /*级联修改门卫：门岗清空、离岗*/
        if(i==1){
            DjbAdmin admin1 = new DjbAdmin();
            admin1.setGateId(id);
            List<DjbAdmin> djbAdmins = adminMapper.selectDjbAdminList(admin1);
            for(DjbAdmin tmp : djbAdmins){
                tmp.setGateId(0);
                tmp.setGateName("");
                tmp.setIsPost(SYS_NO);
                adminMapper.updateDjbAdmin(tmp);
            }
        }
        return AjaxResult.success("删除成功");
    }

    /*门岗新增*/
    @PutMapping("/gateAdd")
    @ResponseBody
    @AdminLoginToken
    public AjaxResult gateAdd(HttpServletRequest request,
                              String name,String address,
                              String longitude,String latitude,
                              Integer isGuard,Integer isRegiste,
                              Integer registeBeginHour,Integer registeBeginMinute,Integer registeEndHour,Integer registeEndMinute,
                              Integer registeType,String keeper,Integer blueToothIn,Integer blueToothOut,Integer guardDevice,String buildingIds){
        DjbAdmin admin = (DjbAdmin) request.getAttribute("admin");
        /*目标：加入重名校验，如有重名提交时提示：该楼座、门岗名称已存在*/
        DjbGate check = new DjbGate();
        check.setName(name);
        check.setDistrictId(admin.getDistrictId());
        List<DjbGate> djbGates = gateMapper.selectDjbGateList(check);
        if(!djbGates.isEmpty()){
            return error("该门岗名称已存在");
        }
        DjbGate add = new DjbGate();
        add.setDistrictId(admin.getDistrictId());
        add.setName(name);
        add.setAddress(address);
        add.setLatitude(latitude);
        add.setLongitude(longitude);
        add.setIsGuard(isGuard);
        add.setIsRegiste(isRegiste);
        /*取消门岗处绑定门卫逻辑*/
//        JSONArray array= new JSONArray();
//        String[] split = keeper.split(",");
//        for(String id : split){
//            DjbAdmin admin1 = adminMapper.selectDjbAdminById(Integer.parseInt(id));
//            JSONObject tmp = new JSONObject();
//            tmp.put("id",id);
//            tmp.put("name",admin1.getName());
//            array.add(tmp);
//        }
//        add.setKeeper(array.toJSONString());
        if(blueToothIn!=null&&blueToothIn!=0){
            add.setBluetoothIn(blueToothIn);
        }
        if(blueToothOut!=null&&blueToothOut!=0){
            add.setBluetoothOut(blueToothOut);
        }
        if(guardDevice!=null&&guardDevice!=0){
            add.setGuardDevice(guardDevice);
        }
        if(isRegiste==SYS_YES){
            add.setRegisteBeginHour(registeBeginHour);
            add.setRegisteBeginMinute(registeBeginMinute);
            add.setRegisteEndHour(registeEndHour);
            add.setRegisteEndMinute(registeEndMinute);
            add.setRegisteType(registeType);
        }
        List<String> buildingNames= new ArrayList<>();
        if(buildingIds!=null && !buildingIds.isEmpty()){
            String[] split = buildingIds.split(",");
            for(String tmp : split){
                DjbBuilding building = buildingMapper.selectDjbBuildingById(Integer.parseInt(tmp));
                if(building!=null){
                    buildingNames.add(building.getName());
                }
            }
            add.setBuildingIds(buildingIds);
            add.setBuildingNames(String.join(",",buildingNames));
        }else{
            add.setBuildingIds("");
            add.setBuildingNames("");
        }
        gateMapper.insertDjbGate(add);
        if(blueToothIn!=null&&blueToothIn!=0){
            DjbDistrictBluetooth djbDistrictBluetooth = bluetoothMapper.selectDjbDistrictBluetoothById(blueToothIn);
            djbDistrictBluetooth.setGateId(add.getId());
            djbDistrictBluetooth.setGateName(add.getName());
            djbDistrictBluetooth.setType("入场");
            bluetoothMapper.updateDjbDistrictBluetooth(djbDistrictBluetooth);
        }
        if(blueToothOut!=null&&blueToothOut!=0){
            DjbDistrictBluetooth djbDistrictBluetooth = bluetoothMapper.selectDjbDistrictBluetoothById(blueToothOut);
            djbDistrictBluetooth.setGateId(add.getId());
            djbDistrictBluetooth.setGateName(add.getName());
            djbDistrictBluetooth.setType("出场");
            bluetoothMapper.updateDjbDistrictBluetooth(djbDistrictBluetooth);
        }
        if(guardDevice!=null&&guardDevice!=0){
            DjbDistrictBluetooth djbDistrictBluetooth = bluetoothMapper.selectDjbDistrictBluetoothById(guardDevice);
            djbDistrictBluetooth.setGateId(add.getId());
            djbDistrictBluetooth.setGateName(add.getName());
            djbDistrictBluetooth.setType("门禁");
            bluetoothMapper.updateDjbDistrictBluetooth(djbDistrictBluetooth);
        }
        JSONObject ret = new JSONObject();
        String base64Person="";
        String base64Car="";
        if(add.getRegisteType()==1){
            base64Person="data:image/jpeg;base64,"+getBase64Code(admin.getDistrictId(),add.getId(),1);
        }else if(add.getRegisteType()==2){
            base64Car="data:image/jpeg;base64,"+getBase64Code(admin.getDistrictId(),add.getId(),2);
        }else{
            base64Person="data:image/jpeg;base64,"+getBase64Code(admin.getDistrictId(),add.getId(),1);
            base64Car="data:image/jpeg;base64,"+getBase64Code(admin.getDistrictId(),add.getId(),2);
        }
        String base64 = "data:image/jpeg;base64,"+getBase64Code(admin.getDistrictId(),add.getId(),null);
//        if(base64.isEmpty()){
//            return error("获取二维码失败");
//        }
        ret.put("base64", base64);
        ret.put("base64Person", base64Person);
        ret.put("base64Car", base64Car);
        ret.put("gate",add);
        return AjaxResult.success("新增成功",ret);
    }

    /*门岗二维码*/
    @GetMapping("/gateQRCode")
    @ResponseBody
    @AdminLoginToken
    public AjaxResult gateQRCode(HttpServletRequest request,Integer id) {
        DjbAdmin admin = (DjbAdmin) request.getAttribute("admin");
        JSONObject ret = new JSONObject();
        DjbGate gate = gateMapper.selectDjbGateById(id);
        String base64Person="";
        String base64Car="";
        if(gate.getRegisteType()==1){
            base64Person="data:image/jpeg;base64,"+getBase64Code(admin.getDistrictId(),id,1);
        }else if(gate.getRegisteType()==2){
            base64Car="data:image/jpeg;base64,"+getBase64Code(admin.getDistrictId(),id,2);
        }else{
            base64Person="data:image/jpeg;base64,"+getBase64Code(admin.getDistrictId(),id,1);
            base64Car="data:image/jpeg;base64,"+getBase64Code(admin.getDistrictId(),id,2);
        }
        String base64 = "data:image/jpeg;base64,"+getBase64Code(admin.getDistrictId(),id,null);
//        if(base64.isEmpty()){
//            return error("获取二维码失败");
//        }
        ret.put("base64", base64);
        ret.put("base64Person", base64Person);
        ret.put("base64Car", base64Car);
        return AjaxResult.success("查询成功", ret);
    }

    /*楼座列表*/
    @GetMapping("/buildingList")
    @ResponseBody
    @AdminLoginToken
    public AjaxResult buildingList(HttpServletRequest request){
        DjbAdmin admin = (DjbAdmin) request.getAttribute("admin");
        DjbBuilding query = new DjbBuilding();
        query.setDistrictId(admin.getDistrictId());
        DjbDistrict djbDistrict = districtMapper.selectDjbDistrictById(admin.getDistrictId());
        List<DjbBuilding> djbBuildings = buildingMapper.selectDjbBuildingList(query);
        if(djbBuildings.isEmpty()){
            return AjaxResult.warn("无记录");
        }
        if(djbDistrict.getType()==BUILDING_TYPE_DEPARTMENT){
            djbBuildings.sort((o1, o2) -> {
                Integer name1 = o1.getVisit();//name1是从你list里面拿出来的一个
                Integer name2 = o2.getVisit();//name1是从你list里面拿出来的一个
                return name2.compareTo(name1);
            });
        }
        JSONObject ret = new JSONObject();
        ret.put("buildingList",djbBuildings);
        return AjaxResult.success("查询成功",ret);
    }

    /*楼座编辑*/
    @PutMapping("/buildingUpdate")
    @ResponseBody
    @AdminLoginToken
    public AjaxResult buildingUpdate(HttpServletRequest request,
                                     Integer id,
                                     String address,
                                     String name,
                                     Integer unit,
                                     Integer floor,
                                     Integer room,
                                     @RequestParam(name = "minFloor",required = false) Integer minFloor,
                                     @RequestParam(name = "minRoom",required = false) Integer minRoom,
                                     String keeper,
                                     @RequestParam(name = "mobile",required = false) String mobile){
        DjbAdmin admin = (DjbAdmin) request.getAttribute("admin");
        DjbBuilding update = buildingMapper.selectDjbBuildingById(id);
        String oldName = update.getName();
        /*目标：加入重名校验，如有重名提交时提示：该楼座、门岗名称已存在*/
        if(!oldName.equals(name)){
            DjbBuilding check = new DjbBuilding();
            check.setName(name);
            check.setDistrictId(admin.getDistrictId());
            List<DjbBuilding> djbBuildings = buildingMapper.selectDjbBuildingList(check);
            if(!djbBuildings.isEmpty()){
                return error("该名称已存在");
            }
        }
        update.setDistrictId(admin.getDistrictId());
        update.setName(name);
        DjbDistrict djbDistrict = districtMapper.selectDjbDistrictById(admin.getDistrictId());
        if(djbDistrict.getType()==BUILDING_TYPE_BUILD){
            update.setUnit(unit);
            update.setFloor(floor);
            if(minFloor!=null){
                update.setMinFloor(minFloor);
            }
            if(minRoom!=null){
                update.setMinRoom(minRoom);
            }
            update.setRoom(room);
            if(keeper.isEmpty()){
                update.setKeeper("[]");
            }else{
                JSONArray array= new JSONArray();
                String[] split = keeper.split(",");
                for(String id2 : split){
                    DjbAdmin admin1 = adminMapper.selectDjbAdminById(Integer.parseInt(id2));
                    JSONObject tmp = new JSONObject();
                    tmp.put("id",id2);
                    tmp.put("name",admin1.getName());
                    array.add(tmp);
                }
                update.setKeeper(array.toJSONString());
            }
        }else if(djbDistrict.getType()==BUILDING_TYPE_COMPANY){
            update.setAddress(address);
        }else {
            update.setMobile(mobile);
        }
        buildingMapper.updateDjbBuilding(update);
        /*如果修改了楼座名称，联动修改住户的楼座名称*/
        if(!name.isEmpty()&&!name.equals(oldName)){
            DjbDistrictUser query = new DjbDistrictUser();
            query.setBuilding(id);
            List<DjbDistrictUser> djbDistrictUsers = districtUserMapper.selectDjbDistrictUserList(query);
            for(DjbDistrictUser tmp : djbDistrictUsers){
                if(djbDistrict.getType()==BUILDING_TYPE_BUILD){
                    tmp.setAddress(name+(tmp.getUnit()==0?"":tmp.getUnit()+"单元")+tmp.getFloor()+String.format("%02d",tmp.getRoom()));
                }else if(djbDistrict.getType()==BUILDING_TYPE_COMPANY){
                    tmp.setAddress(address);
                }
                districtUserMapper.updateDjbDistrictUser(tmp);
            }
        }
        return AjaxResult.success("编辑成功");
    }

    /*楼座删除*/
    @DeleteMapping("/buildingDelete")
    @ResponseBody
    @AdminLoginToken
    public AjaxResult buildingDelete(HttpServletRequest request,Integer id){
        DjbAdmin admin = (DjbAdmin) request.getAttribute("admin");
        DjbBuilding building1 = buildingMapper.selectDjbBuildingById(id);

        int i = buildingMapper.deleteDjbBuildingById(id);
        /*解除该楼座所有住户认证*/
        if(i==1){
            DjbDistrictUser query = new DjbDistrictUser();
            query.setBuilding(id);
            List<DjbDistrictUser> djbDistrictUsers = districtUserMapper.selectDjbDistrictUserList(query);
            for(DjbDistrictUser tmp : djbDistrictUsers){
                tmp.setDistrictId(0);
                tmp.setDistrictName("");
                tmp.setStatus(SYS_STATUS_TODO);
                tmp.setName("");
                tmp.setMobile("");
                tmp.setBuilding(0);
                tmp.setUnit(0);
                tmp.setFloor(0);
                tmp.setRoom(0);
                tmp.setAddress("");
                districtUserMapper.updateDjbDistrictUser(tmp);
            }
        }
        if (building1.getType()==BUILDING_TYPE_DEPARTMENT){
            return AjaxResult.success("删除人员成功");
        }else{
            return AjaxResult.success("删除成功，所有认证在该楼座的住户都已解除认证");
        }
    }

    /*楼座新增*/
    @PutMapping("/buildingAdd")
    @ResponseBody
    @AdminLoginToken
    public AjaxResult buildingAdd(HttpServletRequest request,String address,String name,Integer unit,Integer floor,Integer room,
                                  @RequestParam(name = "minFloor",required = false) Integer minFloor,
                                  @RequestParam(name = "minRoom",required = false) Integer minRoom,
                                  String keeper,
                                  @RequestParam(name = "mobile",required = false) String mobile){
        DjbAdmin admin = (DjbAdmin) request.getAttribute("admin");
        /*目标：加入重名校验，如有重名提交时提示：该楼座、门岗名称已存在*/
        DjbBuilding check = new DjbBuilding();
        check.setName(name);
        check.setDistrictId(admin.getDistrictId());
        List<DjbBuilding> djbBuildings = buildingMapper.selectDjbBuildingList(check);
        if(!djbBuildings.isEmpty()){
            return error("该名称已存在");
        }
        DjbBuilding add = new DjbBuilding();
        add.setDistrictId(admin.getDistrictId());
        add.setName(name);//==2时只需要name.
        DjbDistrict djbDistrict = districtMapper.selectDjbDistrictById(admin.getDistrictId());
        add.setType(djbDistrict.getType());
        if(djbDistrict.getType()==BUILDING_TYPE_BUILD){
            add.setUnit(unit);
            add.setFloor(floor);
            add.setRoom(room);
            if(minFloor!=null){
                add.setMinFloor(minFloor);
            }
            if(minRoom!=null){
                add.setMinRoom(minRoom);
            }
            if(keeper.isEmpty()){
                add.setKeeper("[]");
            }else{
                JSONArray array= new JSONArray();
                String[] split = keeper.split(",");
                for(String id : split){
                    DjbAdmin admin1 = adminMapper.selectDjbAdminById(Integer.parseInt(id));
                    JSONObject tmp = new JSONObject();
                    tmp.put("id",id);
                    tmp.put("name",admin1.getName());
                    array.add(tmp);
                }
                add.setKeeper(array.toJSONString());
            }
        }else if(djbDistrict.getType()==BUILDING_TYPE_COMPANY){
            add.setAddress(address);
        }else {
            add.setMobile(mobile);
        }
        buildingMapper.insertDjbBuilding(add);
        return AjaxResult.success("新增成功");
    }

    /*注销账号*/
    @DeleteMapping("/adminUnRegistry")
    @ResponseBody
    @AdminLoginToken
    public AjaxResult adminUnRegistry(HttpServletRequest request){
        DjbAdmin admin = (DjbAdmin) request.getAttribute("admin");
        if(admin.getType()==ADMIN_TYPE_ADMIN){
            DjbAdmin check = new DjbAdmin();
            check.setDistrictId(admin.getDistrictId());
            check.setType(ADMIN_TYPE_ADMIN);
            List<DjbAdmin> djbAdmins = adminMapper.selectDjbAdminList(check);
            if(djbAdmins.size()==1){
                return error("您是唯一管理员\n无法注销");
            }
        }
        adminMapper.deleteDjbAdminById(admin.getId());
        /*如果是管家，注销后解除楼座绑定*/
        if(admin.getType().equals(ADMIN_TYPE_WUYE)){
            /*显示自己已绑定的楼座*/
            List<Integer> integers = queryBuilding2(admin.getId());
            for(Integer buildingId : integers){
                DjbBuilding building = buildingMapper.selectDjbBuildingById(buildingId);
                String keeper = building.getKeeper();
                JSONArray array = JSONArray.parseArray(keeper);
                for(int i =0;i<array.size();i++){
                    JSONObject jsonObject = array.getJSONObject(i);
                    if(jsonObject.getIntValue("id")==admin.getId()){
                        array.remove(i);
                        break;
                    }
                }
                building.setKeeper(array.toJSONString());
                buildingMapper.updateDjbBuilding(building);
            }
        }
        return AjaxResult.success("注销成功");
    }

    private String getBase64Code(Integer districtId, Integer gateId,Integer type){
        /*type */
        String base64 = "";
        String postUrl = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + getAccessToken();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("page", "pages/VisitorRegistration/VisitorRegistration"); // openid
        if(type==null){
            jsonObject.put("scene", "districtId=" + districtId + "&gateId=" + gateId+"&gt="+0);
        }else{
            jsonObject.put("scene", "districtId=" + districtId + "&gateId=" + gateId+"&gt="+type);
        }
        //正式版为 "release"，体验版为 "trial"，开发版为 "develop"。默认是正式版。
        if(env.equals("PROD")){
            jsonObject.put("env_version", "release");
        }else{
            jsonObject.put("env_version", "trial");
        }
        jsonObject.put("check_path", false);
        try {
            HttpClientBuilder builder = HttpClientBuilder.create();
            CloseableHttpClient client = builder.build();
            HttpPost post = new HttpPost(postUrl);
            // 设置请求的的参数，requestBody
            StringEntity s = new StringEntity(jsonObject.toString());
            s.setContentType("image/png");
            post.setEntity(s);
            HttpResponse response = client.execute(post);
//            HttpEntity entity = response.getEntity();
//            String res = EntityUtils.toString(entity, "utf-8");
//            if(res.contains("errcode")){
//                return error("获取二维码图片失败");
//            }
            InputStream inputStream = response.getEntity().getContent();
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len ;
            while ((len = inputStream.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
            byte[] bytes = out.toByteArray();
            Base64.Encoder encoder = Base64.getEncoder();
            base64 = encoder.encodeToString(bytes);
            client.close();
            return base64;
        } catch (Exception e) {
            e.printStackTrace();
            return base64;
        }
    }

    private String getGZHUserUnionId(String openId){
        String s = HttpUtils.sendGet("https://api.weixin.qq.com/cgi-bin/user/info", "access_token=" + getAccessToken2()+"&openid="+openId);
        JSONObject ret = JSONObject.parseObject(s);

        if(ret.containsKey("errcode")||ret.getIntValue("subscribe")==0){
            return null;
        }
        return ret.getString("unionid");
    }

//    /*关注/取消关注通知*/
//    @GetMapping("/test")
//    @ResponseBody
//    @PassToken
//    @RepeatSubmit
//    public String test(HttpServletRequest request) throws Exception {
//        return request.getParameter("echostr");
//    }

    /*关注/取消关注通知*/
    @PostMapping("/test")
    @ResponseBody
    @PassToken
    @RepeatSubmit
    public String test(HttpServletRequest request) throws Exception {
        BufferedReader reader = request.getReader();
        HashMap<String, String> map = new HashMap<>();
        String line;
        StringBuilder inputString = new StringBuilder();
        while ((line = reader.readLine()) != null) {
            inputString.append(line);
        }
        System.out.println("微信回调通知参数："+inputString.toString());
        request.getReader().close();
        map.put("return_code", "FAIL");
        map.put("return_msg", "FAIL");
        Map<String, String> return_map = WXPayUtil.xmlToMap(inputString.toString());

        String response="";

        /*订阅*/
        if(return_map.containsKey("Event")&&return_map.get("Event").equals("subscribe")){
            String openId = return_map.get("FromUserName");
            /*查询*/
            String unionId = getGZHUserUnionId(openId);
            if(unionId==null){
                return response;
            }
            DjbUser djbUser = userMapper.selectDjbUserByUnionId(unionId);
            if(djbUser!=null){
                djbUser.setOpenId2(openId);
                userMapper.updateDjbUser(djbUser);
            }
            DjbAdmin admin = adminMapper.selectDjbAdminByUnionId(unionId);
            if(admin!=null){
                admin.setOpenId2(openId);
                adminMapper.updateDjbAdmin(admin);
            }
            Map<String, String> data = new HashMap<>();
            data.put("ToUserName",openId);
            data.put("FromUserName","gh_b0af42613615");
            data.put("CreateTime",String.valueOf(System.currentTimeMillis()/ 1000));
            data.put("MsgType","text");
            data.put("Content","欢迎您使用小门官访客登记系统，点击左下角“访客登记”可实现远程登记，点击右下角“立即入驻”获取最专业的访客预约登记解决方案。");
            response = WXPayUtil.mapToXml(data);
        }else if(return_map.containsKey("Event")&&return_map.get("Event").equals("unsubscribe")){
            /*取消订阅*/
            String openId = return_map.get("FromUserName");
            DjbUser djbUser = userMapper.selectDjbUserByGZHOpenId(openId);
            if(djbUser!=null){
                djbUser.setOpenId2("");
                userMapper.updateDjbUser(djbUser);
            }
            DjbAdmin admin = adminMapper.selectAdminByGZHOpenId(openId);
            if(admin!=null){
                admin.setOpenId2("");
                adminMapper.updateDjbAdmin(admin);
            }
        }
        return response;
    }

    /*摄像头推送*/
    @PostMapping("/imagePush")
    @ResponseBody
    @PassToken
    public AjaxResult imagePush(HttpServletRequest request,@RequestBody JSONObject body) throws Exception {
        System.out.println(body.toJSONString());
        AjaxResult ajaxResult = new AjaxResult();
        JSONObject info = new JSONObject();
        info.put("info","ok");
        ajaxResult.put("Response_AlarmInfoPlate",info);
        return ajaxResult;
    }

    /*摄像头轮询*/
    @PostMapping("/imageComet")
    @ResponseBody
    @PassToken
    public AjaxResult imagePush(HttpServletRequest request,int channel_num,String device_name,String ipaddr,String pass_wd,String port,String serialno) throws Exception {
        System.out.println(channel_num);
        System.out.println(device_name);
        System.out.println(ipaddr);
        System.out.println(pass_wd);
        System.out.println(port);
        System.out.println(serialno);

        AjaxResult ajaxResult = new AjaxResult();
        JSONObject info = new JSONObject();
        info.put("info","ok");
        ajaxResult.put("Response_AlarmInfoPlate",info);


        return ajaxResult;
    }

    /*显示自己为登记地址所在楼座最高级管家的楼座*/
    private List<Integer> queryBuilding(int adminId){
        DjbBuilding djbBuilding = new DjbBuilding();
        djbBuilding.setKeeper("\"id\":\""+adminId+"\"");
        List<DjbBuilding> djbBuildings = buildingMapper.selectDjbBuildingList(djbBuilding);
        List<Integer> ids = new ArrayList<>();
        for(DjbBuilding building : djbBuildings){
            JSONArray parse = JSONArray.parseArray(building.getKeeper());
            for(int i=0;i<parse.size();i++){
                JSONObject jsonObject = parse.getJSONObject(i);
                int id = jsonObject.getIntValue("id");
                DjbAdmin admin = adminMapper.selectDjbAdminById(id);
                if(admin==null) continue;
                if(admin.getIsPost()==SYS_NO) continue;
                if(admin.getId()==adminId) {
                    if(!ids.contains(building.getId())){
                        ids.add(building.getId());
                    }
                }
                break;
            }
        }
        return  ids;
    }

    /*显示自己已绑定的楼座*/
    private List<Integer> queryBuilding2(int adminId){
        DjbBuilding djbBuilding = new DjbBuilding();
        djbBuilding.setKeeper("\"id\":\""+adminId+"\"");
        List<DjbBuilding> djbBuildings = buildingMapper.selectDjbBuildingList(djbBuilding);
        List<Integer> ids = new ArrayList<>();
        for(DjbBuilding building : djbBuildings){
            ids.add(building.getId());
        }
        return ids;
    }

    /*查询菜单*/
    @GetMapping("/menuList")
    @ResponseBody
    @PassToken
    public AjaxResult menuList(HttpServletRequest request){
        String token=getAccessToken2();
        String url = "https://api.weixin.qq.com/cgi-bin/get_current_selfmenu_info?access_token=" + token;
        String s = HttpUtils.sendGet(url, "");
        System.out.println(s);
        JSONObject jsonObject = JSONObject.parseObject(s);
        return AjaxResult.success("查询成功",jsonObject.toJSONString());
    }

    /*设置菜单*/
    @PutMapping("/menuSet")
    @ResponseBody
    @PassToken
    public AjaxResult menuSet(HttpServletRequest request) throws Exception {
        String token=getAccessToken2();
        String url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" + token;
        JSONObject jsonObject = JSONObject.parseObject("{\"button\":[{\"pagepath\":\"/pages/Homepage/Homepage\",\"appid\":\"wx023fe513b09669b7\",\"name\":\"访客登记\",\"type\":\"miniprogram\",\"url\":\"\"},{\"name\":\"我的登记\",\"type\":\"miniprogram\",\"url\":\"\",\"pagepath\":\"/pages/MyRegistrationList/MyRegistrationList\",\"appid\":\"wx023fe513b09669b7\"},{\"name\":\"立即入驻\",\"type\":\"view\",\"url\":\"https://work.weixin.qq.com/kfid/kfc133958c52f51c6c1\"}]}");
        String s = HttpUtils.httpPostJson(url, jsonObject);
        return success(s);
    }

    /*登记出场*/
    @PutMapping("/registryOut")
    @ResponseBody
    @AdminLoginToken
    public AjaxResult registryOut(HttpServletRequest request,Integer id){
        DjbAdmin admin = (DjbAdmin) request.getAttribute("admin");
        DjbRelease release = releaseMapper.selectDjbReleaseById(id);
        if(release==null){
            return error("放行记录不存在");
        }
        DjbGate gate = gateMapper.selectDjbGateById(admin.getGateId());
        if(gate!=null){
            release.setOutGate(gate.getName());
        }else{
            release.setOutGate("无");
        }
        release.setOutTime(DateUtils.getNowDate());
        release.setOutName(admin.getName());
        releaseMapper.updateDjbRelease(release);
        Integer regId = release.getRegId();
        DjbRegistry registry = registryMapper.selectDjbRegistryById(regId);
        if(registry!=null){
            registry.setStatus(SYS_STATUS_OUT);
            registryMapper.updateDjbRegistry(registry);
        }
        /*如果放行的是车辆，且小区开了最大车辆限制,则车辆数加1*/
        if(release.getUserType()==1){
            DjbDistrict djbDistrict = districtMapper.selectDjbDistrictById(admin.getDistrictId());
            if(djbDistrict.getMaxCar()!=0){
                djbDistrict.setCurrentCar(Math.max(djbDistrict.getCurrentCar()-1,0));
                districtMapper.updateDjbDistrict(djbDistrict);
            }
        }
        return AjaxResult.success("出场成功");
    }

    /*修改快捷起落开关*/
    @PutMapping("/updateFastOpenSwitch")
    @ResponseBody
    @AdminLoginToken
    public AjaxResult registryOut(HttpServletRequest request,String type,int state){
        DjbAdmin admin = (DjbAdmin) request.getAttribute("admin");
        DjbDistrict djbDistrict = districtMapper.selectDjbDistrictById(admin.getDistrictId());
        if(type.equals("out")){
            djbDistrict.setFastOpenSwitchOut(state);
        }else{
            djbDistrict.setFastOpenSwitchIn(state);
        }
        districtMapper.updateDjbDistrict(djbDistrict);
        return AjaxResult.success("设置成功");
    }

    /*设备列表*/
    @GetMapping("/blueToothList")
    @ResponseBody
    @AdminLoginToken
    public AjaxResult blueToothList(HttpServletRequest request){
        DjbAdmin admin = (DjbAdmin) request.getAttribute("admin");
        DjbDistrictBluetooth bluetooth = new DjbDistrictBluetooth();
        bluetooth.setDistrictId(admin.getDistrictId());
        List<DjbDistrictBluetooth> djbDistrictBluetooths = bluetoothMapper.selectDjbDistrictBluetoothList(bluetooth);
        if(djbDistrictBluetooths.isEmpty()){
            return AjaxResult.warn("无记录");
        }
        for(DjbDistrictBluetooth tmp: djbDistrictBluetooths){
            if(tmp.getGateId()!=null){
                DjbGate gate = gateMapper.selectDjbGateById(tmp.getGateId());
                if(gate!=null) tmp.setGateName(gate.getName());
            }
        }
        JSONObject ret = new JSONObject();
        ret.put("blueToothList",djbDistrictBluetooths);
        return AjaxResult.success("查询成功",ret);
    }

    /*绑定设备*/
    @GetMapping("/BindBlueTooth")
    @ResponseBody
    @AdminLoginToken
    public AjaxResult BindBlueTooth(HttpServletRequest request,int gateId,int blueToothId){
        DjbAdmin admin = (DjbAdmin) request.getAttribute("admin");
        DjbDistrictBluetooth bluetooth = new DjbDistrictBluetooth();
        bluetooth.setDistrictId(admin.getDistrictId());
        List<DjbDistrictBluetooth> djbDistrictBluetooths = bluetoothMapper.selectDjbDistrictBluetoothList(bluetooth);
        if(djbDistrictBluetooths.isEmpty()){
            return AjaxResult.warn("无记录");
        }
        for(DjbDistrictBluetooth tmp: djbDistrictBluetooths){
            if(tmp.getGateId()!=null){
                DjbGate gate = gateMapper.selectDjbGateById(tmp.getGateId());
                if(gate!=null) tmp.setGateName(gate.getName());
            }
        }
        JSONObject ret = new JSONObject();
        ret.put("blueToothList",djbDistrictBluetooths);
        return AjaxResult.success("查询成功",ret);
    }

    /*事由列表*/
    @GetMapping("/reasonList")
    @ResponseBody
    @AdminLoginToken
    public AjaxResult reasonList(HttpServletRequest request){
        DjbAdmin admin = (DjbAdmin) request.getAttribute("admin");
        DjbReason reason = new DjbReason();
        reason.setDistrictId(admin.getDistrictId());
        List<DjbReason> djbReasons = reasonMapper.selectDjbReasonList(reason);
        if(djbReasons.isEmpty()){
            DjbDistrict djbDistrict = districtMapper.selectDjbDistrictById(admin.getDistrictId());
            initDjbReason(admin.getDistrictId(),djbDistrict.getType());
            djbReasons = reasonMapper.selectDjbReasonList(reason);
        }
        JSONObject ret = new JSONObject();
        ret.put("reasonList",djbReasons);
        return AjaxResult.success("查询成功",ret);
    }

    /*事由新增*/
    @PutMapping("/reasonAdd")
    @ResponseBody
    @AdminLoginToken
    public AjaxResult reasonAdd(HttpServletRequest request,String reason){
        DjbAdmin admin = (DjbAdmin) request.getAttribute("admin");
        DjbReason djbReason1 = new DjbReason();
        djbReason1.setDistrictId(admin.getDistrictId());
        djbReason1.setReason(reason);
        djbReason1.setType(1);
        djbReason1.setIsOpen(0);
        reasonMapper.insertDjbReason(djbReason1);
        return AjaxResult.success("添加成功",djbReason1);
    }

    /*事由删除*/
    @DeleteMapping("/reasonDelete")
    @ResponseBody
    @AdminLoginToken
    public AjaxResult reasonDelete(HttpServletRequest request,Integer id){
        DjbAdmin admin = (DjbAdmin) request.getAttribute("admin");
        reasonMapper.deleteDjbReasonById(id);
        return AjaxResult.success("删除成功");
    }

    /*登记管理*/
    @PutMapping("/districtReasonsUpdate")
    @ResponseBody
    @AdminLoginToken
    public AjaxResult districtReasonsUpdate(HttpServletRequest request,Integer addressSwitch,Integer reasonSwitch,String ids,
                                            Integer departmentSwitch,Integer remarkSwitch,Integer idNumberSwitch,Integer userSwitch){
        DjbAdmin admin = (DjbAdmin) request.getAttribute("admin");
        DjbDistrict djbDistrict = districtMapper.selectDjbDistrictById(admin.getDistrictId());
        djbDistrict.setReasonSwitch(reasonSwitch);
        djbDistrict.setAddressSwitch(addressSwitch);
        if(reasonSwitch==1){
            DjbReason reason = new DjbReason();
            reason.setDistrictId(admin.getDistrictId());
            List<DjbReason> djbReasons = reasonMapper.selectDjbReasonList(reason);
            String[] split = ids.split(",");
            for(DjbReason tmp : djbReasons){
                tmp.setIsOpen(0);
                tmp.setRanks(0);
                reasonMapper.updateDjbReason(tmp);
            }
            int i=1;
            for(String id:split){
                DjbReason reason1 = reasonMapper.selectDjbReasonById(Integer.parseInt(id));
                reason1.setIsOpen(1);
                reason1.setRanks(i);
                reasonMapper.updateDjbReason(reason1);
                i++;
            }
        }
        if(departmentSwitch!=null){
            djbDistrict.setDepartmentSwitch(departmentSwitch);
        }
        if(remarkSwitch!=null){
            djbDistrict.setRemarkSwitch(remarkSwitch);
        }
        if(idNumberSwitch!=null){
            djbDistrict.setIdNumberSwitch(idNumberSwitch);
        }
        if(userSwitch!=null){
            djbDistrict.setUserSwitch(userSwitch);
        }
        districtMapper.updateDjbDistrict(djbDistrict);
        return AjaxResult.success("修改成功");
    }

    /*最大车辆数设置*/
    @PutMapping("/districtMaxCarSet")
    @ResponseBody
    @AdminLoginToken
    public AjaxResult districtMaxCarSet(HttpServletRequest request,Integer maxCar){
        DjbAdmin admin = (DjbAdmin) request.getAttribute("admin");
        DjbDistrict djbDistrict = districtMapper.selectDjbDistrictById(admin.getDistrictId());
        djbDistrict.setMaxCar(maxCar);
        districtMapper.updateDjbDistrict(djbDistrict);
        return AjaxResult.success("修改成功");
    }

    /*当前车辆数设置*/
    @PutMapping("/districtCurrentCarSet")
    @ResponseBody
    @AdminLoginToken
    public AjaxResult districtCurrentCarSet(HttpServletRequest request,Integer currentCar){
        DjbAdmin admin = (DjbAdmin) request.getAttribute("admin");
        DjbDistrict djbDistrict = districtMapper.selectDjbDistrictById(admin.getDistrictId());
        if(currentCar>djbDistrict.getMaxCar()){
            return error("当前车辆数不能大于最大车辆数限制");
        }
        djbDistrict.setCurrentCar(currentCar);
        districtMapper.updateDjbDistrict(djbDistrict);
        return AjaxResult.success("修改成功");
    }

    /*车辆数查询*/
    @GetMapping("/districtMaxCarCheck")
    @ResponseBody
    @AdminLoginToken
    public AjaxResult districtMaxCarCheck(HttpServletRequest request){
        DjbAdmin admin = (DjbAdmin) request.getAttribute("admin");
        DjbDistrict djbDistrict = districtMapper.selectDjbDistrictById(admin.getDistrictId());
        JSONObject ret = new JSONObject();
        ret.put("maxCar",djbDistrict.getMaxCar());
        ret.put("currentCar",djbDistrict.getCurrentCar());
        return AjaxResult.success("查询成功",ret);
    }

    /*发送验证码*/
    @GetMapping("/sendMsg")
    @ResponseBody
    @PassToken
    @RepeatSubmit
    @CrossOrigin
    public  AjaxResult sendMsg(@RequestParam("phone") String phone) {
        if(phone.length()!=11){
            return AjaxResult.error("手机号格式错误");
        }
        /*
         * 查询状态正常的验证码
         * */
        DjbPhoneCode phoneCode = phoneCodeMapper.selectDjbPhoneCodeByPhone(phone);
        if(phoneCode!=null ){
            if(DateUtils.differentMillissByMillisecond(phoneCode.getCreateTime(),DateUtils.getNowDate())<600){
                return error("验证码已发送且在有效期内，如长时间未收到请联系客服");
            }else{
                phoneCode.setStatus(0);
                phoneCodeMapper.updateDjbPhoneCode(phoneCode);
            }
        }
        int num= (int)((Math.random()*9+1)*100000);
        DefaultProfile profile = DefaultProfile.getProfile("cn-qingdao", "LTAIw5DUpj6wdXJ2", "dJQG5ShMic015K9lVdEbhvSOM7wfbr");
        IAcsClient client = new DefaultAcsClient(profile);
        CommonRequest request;
        request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("SignName", "小门官");
        request.putQueryParameter("TemplateCode", "SMS_472350021");
        JSONObject jo=new JSONObject();
        jo.put("code",num);
        request.putQueryParameter("TemplateParam", jo.toString());
        try {
            CommonResponse response2 = client.getCommonResponse(request);
            jo=JSONObject.parseObject(response2.getData());
            if(jo.getString("Code").equals("OK")){
                /*保存验证码*/
                DjbPhoneCode phoneCode2=new DjbPhoneCode();
                phoneCode2.setPhone(phone);
                phoneCode2.setCode(String.valueOf(num));
                phoneCode2.setStatus(1);
                phoneCode2.setCreateTime(DateUtils.getNowDate());
                phoneCodeMapper.insertDjbPhoneCode(phoneCode2);
            }else{
                return AjaxResult.error("发送失败，请联系客服");
            }
        } catch (ClientException e) {
            e.printStackTrace();
            logger.error("发送短信错误:"+e.getMessage());
            return AjaxResult.error("发送失败，请联系客服");
        }
        return AjaxResult.success("发送成功");
    }

    /*校验手机验证码*/
    public  boolean checkPhoneCode(String phone,int code){
        if(!env.equals("PROD")){
            return true;
        }
        DjbPhoneCode phoneCode1 = phoneCodeMapper.selectDjbPhoneCodeByPhone(phone);
        if(phoneCode1==null || !phoneCode1.getCode().equals(String.valueOf(code)) || DateUtils.differentMillissByMillisecond(phoneCode1.getCreateTime(),DateUtils.getNowDate())>600){
            return false;
        }
        phoneCode1.setStatus(0);
        phoneCodeMapper.updateDjbPhoneCode(phoneCode1);
        return true;
    }

    /*登记已纠错*/
    @PutMapping("/registryReError")
    @ResponseBody
    @AdminLoginToken
    public AjaxResult registryReError(HttpServletRequest request,Integer id){
        DjbAdmin admin = (DjbAdmin) request.getAttribute("admin");
        DjbRegistry registry = registryMapper.selectDjbRegistryById(id);
        if(registry!=null){
            registry.setStatus(SYS_STATUS_WRONG);
            registryMapper.updateDjbRegistry(registry);
        }
        return AjaxResult.success("纠错成功");
    }

    /*门岗和楼座新增测试版*/
    @PutMapping("/gateAndBuildingAdd")
    @ResponseBody
    @AdminLoginToken
    public AjaxResult gateAndBuildingAdd(HttpServletRequest request){
        DjbAdmin admin = (DjbAdmin) request.getAttribute("admin");
        DjbDistrict djbDistrict = districtMapper.selectDjbDistrictById(admin.getDistrictId());
        DjbGate check = new DjbGate();
        check.setDistrictId(admin.getDistrictId());
        List<DjbGate> djbGates = gateMapper.selectDjbGateList(check);
        JSONObject ret = new JSONObject();
        ret.put("addGate",false);
        DjbGate add = new DjbGate();
        if(djbGates.isEmpty()){
            add.setDistrictId(admin.getDistrictId());
            add.setName("测试门岗");
            add.setAddress(djbDistrict.getAddress());
            add.setLatitude(djbDistrict.getLatitude());
            add.setLongitude(djbDistrict.getLongitude());
            add.setIsGuard(1);
            add.setIsRegiste(1);
            add.setRegisteBeginHour(0);
            add.setRegisteBeginMinute(0);
            add.setRegisteEndHour(23);
            add.setRegisteEndMinute(59);
            add.setRegisteType(2);
            gateMapper.insertDjbGate(add);
        }else{
            add = djbGates.get(0);
        }
        String base64Person="";
        String base64Car="";
        if(add.getRegisteType()==1){
            base64Person="data:image/jpeg;base64,"+getBase64Code(admin.getDistrictId(),add.getId(),1);
        }else if(add.getRegisteType()==2){
            base64Car="data:image/jpeg;base64,"+getBase64Code(admin.getDistrictId(),add.getId(),2);
        }else{
            base64Person="data:image/jpeg;base64,"+getBase64Code(admin.getDistrictId(),add.getId(),1);
            base64Car="data:image/jpeg;base64,"+getBase64Code(admin.getDistrictId(),add.getId(),2);
        }
        String base64 = "data:image/jpeg;base64,"+getBase64Code(admin.getDistrictId(),add.getId(),null);
        ret.put("gate",add);
        ret.put("addGate",true);
        ret.put("base64", base64);
        ret.put("base64Person", base64Person);
        ret.put("base64Car", base64Car);
        DjbBuilding check2 = new DjbBuilding();
        check2.setDistrictId(admin.getDistrictId());
        List<DjbBuilding> djbBuildings = buildingMapper.selectDjbBuildingList(check2);
        if(djbBuildings.isEmpty()){
            DjbBuilding add2 = new DjbBuilding();
            add2.setDistrictId(admin.getDistrictId());
            if(djbDistrict.getType()==BUILDING_TYPE_BUILD){
                add2.setName("测试楼座");
                add2.setUnit(1);
                add2.setFloor(1);
                add2.setRoom(1);
                add2.setMinFloor(1);
                add2.setMinRoom(1);
                add2.setKeeper("[]");
                add2.setType(1);
            }else if(djbDistrict.getType()==BUILDING_TYPE_DEPARTMENT){
                add2.setName("测试人员");
                add2.setType(2);
                add2.setMobile("13300010001");
            }else if(djbDistrict.getType()==BUILDING_TYPE_COMPANY){
                add2.setName("测试公司");
                add2.setAddress("测试公司的地址");
                add2.setType(3);
            }
            buildingMapper.insertDjbBuilding(add2);
        }
        return AjaxResult.success("新增成功",ret);
    }

    /*同一行人月度来访次数限制设置*/
    @PutMapping("/userMaxMonthSet")
    @ResponseBody
    @AdminLoginToken
    public AjaxResult userMaxMonthSet(HttpServletRequest request,Integer maxUser){
        DjbAdmin admin = (DjbAdmin) request.getAttribute("admin");
        DjbDistrict djbDistrict = districtMapper.selectDjbDistrictById(admin.getDistrictId());
        djbDistrict.setUserMaxMonth(maxUser);
        districtMapper.updateDjbDistrict(djbDistrict);
        return AjaxResult.success("修改成功");
    }

    /*同一车辆月度来访次数限制设置*/
    @PutMapping("/carMaxMonthSet")
    @ResponseBody
    @AdminLoginToken
    public AjaxResult carMaxMonthSet(HttpServletRequest request,Integer maxCar){
        DjbAdmin admin = (DjbAdmin) request.getAttribute("admin");
        DjbDistrict djbDistrict = districtMapper.selectDjbDistrictById(admin.getDistrictId());
        djbDistrict.setCarMaxMonth(maxCar);
        districtMapper.updateDjbDistrict(djbDistrict);
        return AjaxResult.success("修改成功");
    }

    /*自动放行设置*/
    @PutMapping("/autoReleaseSwitchSet")
    @ResponseBody
    @AdminLoginToken
    public AjaxResult autoReleaseSwitchSet(HttpServletRequest request
            ,Integer autoReleaseSwitch
            ,Integer autoReleaseSwitchMan
            ,Integer autoReleaseSwitchFirst
            ,Integer autoReleaseSwitchTag
            ,Integer autoReleaseSwitchManFirst
            ,Integer autoReleaseSwitchManTag){
        DjbAdmin admin = (DjbAdmin) request.getAttribute("admin");
        DjbDistrict djbDistrict = districtMapper.selectDjbDistrictById(admin.getDistrictId());
        djbDistrict.setAutoReleaseSwitch(autoReleaseSwitch);
        if(autoReleaseSwitchMan!=null){
            djbDistrict.setAutoReleaseSwitchMan(autoReleaseSwitchMan);
            djbDistrict.setAutoReleaseSwitchFirst(autoReleaseSwitchFirst);
            djbDistrict.setAutoReleaseSwitchTag(autoReleaseSwitchTag);
            djbDistrict.setAutoReleaseSwitchManFirst(autoReleaseSwitchManFirst);
            djbDistrict.setAutoReleaseSwitchManTag(autoReleaseSwitchManTag);
        }
        districtMapper.updateDjbDistrict(djbDistrict);
        return AjaxResult.success("修改成功");
    }

    /*登记渠道管理*/
    @PutMapping("/regChannelManage")
    @ResponseBody
    @AdminLoginToken
    public AjaxResult regChannelManage(HttpServletRequest request
            ,Integer regSwitchUserScan
            ,Integer regSwitchUserScanVoice
            ,Integer regSwitchUserRemote
            ,Integer regSwitchUserRemoteVoice
            ,Integer regSwitchUserInvite
            ,Integer regSwitchAdmin){
        DjbAdmin admin = (DjbAdmin) request.getAttribute("admin");
        DjbDistrict djbDistrict = districtMapper.selectDjbDistrictById(admin.getDistrictId());
        djbDistrict.setRegSwitchUserScan(regSwitchUserScan);
        djbDistrict.setRegSwitchUserScanVoice(regSwitchUserScanVoice);
        djbDistrict.setRegSwitchUserRemote(regSwitchUserRemote);
        djbDistrict.setRegSwitchUserRemoteVoice(regSwitchUserRemoteVoice);
        djbDistrict.setRegSwitchUserInvite(regSwitchUserInvite);
        djbDistrict.setRegSwitchAdmin(regSwitchAdmin);
        districtMapper.updateDjbDistrict(djbDistrict);
        return AjaxResult.success("修改成功");
    }

    /*小门官广告监听*/
    @GetMapping("/adIntercept")
    @ResponseBody
    @PassToken
    public AjaxResult adIntercept(HttpServletRequest request){
        Map<String, String[]> maps =  request.getParameterMap();
        for (Map.Entry<String, String[]> entry : maps.entrySet()) {
            String cs = "参数"+entry.getKey() + ":"+ Arrays.toString(entry.getValue())+";";
            System.out.println(cs);
        }
        return AjaxResult.success("修改成功");
    }

    /*访客停留时长管理*/
    @PutMapping("/carRestSet")
    @ResponseBody
    @AdminLoginToken
    public AjaxResult carRestSet(HttpServletRequest request,Integer carRestSwitch,Integer carRestTime,Integer carRestFlag,Integer carRestSms){
        if(carRestSwitch==1&&carRestTime<1){
            return error("时间不能小于1分钟");
        }
        DjbAdmin admin = (DjbAdmin) request.getAttribute("admin");
        DjbDistrict djbDistrict = districtMapper.selectDjbDistrictById(admin.getDistrictId());
        djbDistrict.setCarRestSwitch(carRestSwitch);
        djbDistrict.setCarRestTime(carRestTime);
        djbDistrict.setCarRestFlag(carRestFlag);
        djbDistrict.setCarRestSms(carRestSms);
        districtMapper.updateDjbDistrict(djbDistrict);
        return AjaxResult.success("修改成功");
    }

    /*充值列表*/
    @GetMapping("/chargeList")
    @ResponseBody
    @PassToken
    public  AjaxResult chargeList(){
        List<DjbChargeGradient> list= chargeGradientMapper.selectDjbChargeGradientList(new DjbChargeGradient());
        if(list.isEmpty()){
            return AjaxResult.error("查询结果为空");
        }
        return AjaxResult.success("成功",list);
    }

    /*预支付充值订单*/
    @PostMapping("/prepay")
    @AdminLoginToken
    @ResponseBody
    public AjaxResult prepayCharge(HttpServletRequest request ,@RequestParam("chargeID") Integer chargeID,@RequestParam("payType") String payType) throws Exception {
        DjbAdmin admin = (DjbAdmin) request.getAttribute("admin");
        DjbChargeGradient gradient = chargeGradientMapper.selectDjbChargeGradientById(chargeID);
        if(gradient==null){
            return error("充值ID不存在");
        }
        DjbDistrict district = districtMapper.selectDjbDistrictById(admin.getDistrictId());
        Date now = DateUtils.getNowDate();
        DjbTrade djbTrade = new DjbTrade();
        djbTrade.setChargeId(chargeID);
        djbTrade.setDistrictId(admin.getDistrictId());
        djbTrade.setUserId(admin.getId());
        djbTrade.setMoney(gradient.getMoney());
        djbTrade.setCreateTime(now);
        djbTrade.setTradeTime(now);
        djbTrade.setPayType(payType);
        djbTrade.setStatus(SYS_NO);
        djbTrade.setName("充值");
        djbTrade.setDirect("入");
        djbTrade.setTradeType("充值");
        djbTrade.setBalance(district.getBalance());
        tradeMapper.insertDjbTrade(djbTrade);
        String order_no = djbTrade.getId().toString();
        Map<String, String> result = new HashMap<>();
        /*查询支付配置*/
        switch (payType) {
            case "微信":
                String order_amount = String.valueOf(gradient.getMoney());
                Map<String, String> reqData = new HashMap<>();
                reqData.put("body", "小门官充值");/*充值业务*/
                reqData.put("out_trade_no", order_no);
                reqData.put("total_fee", order_amount);
                reqData.put("spbill_create_ip", IpUtils.getHostIp());
                reqData.put("trade_type", "APP");
                String appKey ="";
                String appid = "chargeConfig.getWxAppid()";
                String mch_id = "chargeConfig.getWxMchid()";
                String notify_url = "chargeConfig.getWxNotifyurl()";
                reqData.put("appid",appid);
                reqData.put("mch_id", mch_id);
                reqData.put("notify_url", notify_url);
                /*统一下单接口 获取预支付 prepayid*/
                Map<String, String> respData = WXPayUtil.wxPay(reqData,appKey);
                if (!respData.get("return_code").equals("SUCCESS")|| !respData.get("result_code").equals("SUCCESS")) {
                    return AjaxResult.error("获取预支付失败");
                }
                // 组装数据返回前端
                String prepay_id = respData.get("prepay_id");
                result.put("appid", appid);
                result.put("partnerid", mch_id);
                result.put("prepayid", prepay_id);
                result.put("noncestr", reqData.get("nonce_str"));
                result.put("timestamp",String.valueOf(WXPayUtil.getCurrentTimestamp()));
                result.put("package", "Sign=WXPay");
                String sign = WXPayUtil.generateSignature(result,appKey, WXPayConstants.SignType.MD5);
                result.put("sign", sign);
                result.put("total_fee", order_amount);
                result.put("order_no", order_no);
                break;
            case "支付宝":
                return error("不支持支付宝");
//                String ali_notify_url=chargeConfig.getAliNotifyurl();
//                AlipayClient alipayClient = getAliPayClient();
//                // 实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
//                AlipayTradeAppPayRequest alipayTradeAppPayRequest = new AlipayTradeAppPayRequest();
//                // SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
//                AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
//                model.setSubject("小门官充值");
//                model.setOutTradeNo(order_no);
//                model.setTimeoutExpress("30m");
//                model.setTotalAmount(money);
//                if(djbTrade.getRemark()!=null && djbTrade.getRemark().equals("sign")){
//                    DxbChargeGradient gradient = chargeGradientService.selectDxbChargeGradientById(chargeID);
//                    model.setProductCode("CYCLE_PAY_AUTH");
//                    SignParams signParams = new SignParams();
//                    signParams.setPersonalProductCode("CYCLE_PAY_AUTH_P");
//                    signParams.setSignScene("INDUSTRY|CARRENTAL");
//                    signParams.setExternalAgreementNo(userInfo.getId().toString());
//                    if(!env.equals("PROD")){
//                        signParams.setSignNotifyUrl("http://dxbtest.dianxiaobao.top:8086/dxb2/charge/AliPaySignNotify");
//                    }else{
//                        signParams.setSignNotifyUrl("http://dxbprod.dianxiaobao.top:8086/dxb2/charge/AliPaySignNotify");
//                    }
//                    AccessParams accessParams = new AccessParams();
//                    accessParams.setChannel("ALIPAYAPP");
//                    signParams.setAccessParams(accessParams);
//                    PeriodRuleParams periodRuleParams = new PeriodRuleParams();
//                    periodRuleParams.setPeriodType("DAY");
//                    if(!env.equals("PROD")){
//                        periodRuleParams.setPeriod(7L);
//                    }else{
//                        periodRuleParams.setPeriod(30L);
//                    }
//                    Date exe= DateUtils.addDays(userInfo.getExpireTime().before(now)?now:userInfo.getExpireTime(),gradient.getDay());
//                    periodRuleParams.setExecuteTime(DateUtils.parseDateToStr(YYYY_MM_DD,exe));
//                    periodRuleParams.setSingleAmount("12.9");
//                    signParams.setPeriodRuleParams(periodRuleParams);
//                    model.setAgreementSignParams(signParams);
//                }
//                alipayTradeAppPayRequest.setBizModel(model);
//                alipayTradeAppPayRequest.setNotifyUrl(ali_notify_url);
//                try {
//                    AlipayTradeAppPayResponse response = alipayClient.sdkExecute(alipayTradeAppPayRequest);
//                    result.put("aliRsp",response.getBody());
//                } catch (AlipayApiException e) {
//                    return AjaxResult.error("支付宝获取预支付订单失败");
//                }
            default:
                return AjaxResult.error("支付方式payType错误");
        }
        JSONObject ret = new JSONObject();
        ret.put("orderID",djbTrade.getId());
        ret.put("result",result);
        return AjaxResult.success(ret);
    }

    /*微信异步通知*/
    @PassToken
    @PostMapping("/WXPayNotify")
    @ResponseBody
    public String WXPayNotify(HttpServletRequest request ) throws Exception {
        BufferedReader reader = null;
        HashMap<String, String> map = new HashMap<>();
        try {
            reader = request.getReader();
            String line;
            StringBuilder inputString = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                inputString.append(line);
            }
            System.out.println("微信回调通知参数："+inputString.toString());
            request.getReader().close();

            map.put("return_code", "FAIL");
            map.put("return_msg", "FAIL");
            Map<String, String> return_map = WXPayUtil.xmlToMap(inputString.toString());
            if (!return_map.get("return_code").equals("SUCCESS") || !return_map.get("result_code").equals("SUCCESS")){
                logger.error("微信异步通知失败,原因:return_code或者result_code错误,详细信息:"+inputString.toString());
                return WXPayUtil.mapToXml(map);
            }
            /*验签*/
            String order_id = return_map.get("out_trade_no");
            DjbTrade trade = tradeMapper.selectDjbTradeById(Integer.valueOf(order_id));
            DjbDistrict district = districtMapper.selectDjbDistrictById(trade.getDistrictId());
            /*查询支付配置*/

            if (!WXPayUtil.isSignatureValid(return_map,"chargeConfig.getWxAppkey()", WXPayConstants.SignType.MD5)) {
                logger.error("微信异步通知失败,原因:验签失败,详细信息:"+inputString.toString());
                return WXPayUtil.mapToXml(map);
            }
            int order_amount = Integer.parseInt(return_map.get("total_fee"));

            if(order_amount!=trade.getMoney()){
                logger.error("微信异步通知失败,原因:订单号不存在或者金额不一致,详细信息:"+inputString.toString());
                return WXPayUtil.mapToXml(map);
            }
            if(trade.getStatus()==SYS_YES){
                map.replace("return_msg", "OK");
                map.replace("return_code", "SUCCESS");
                return WXPayUtil.mapToXml(map);
            }
            /*业务处理*/
            if(!handleChargeOrder(order_id,return_map.get("transaction_id"))){
                logger.error("微信异步通知失败,原因:业务处理失败,详细信息:"+inputString.toString());
                return WXPayUtil.mapToXml(map);
            }
            map.replace("return_msg", "OK");
            map.replace("return_code", "SUCCESS");
            logger.info("微信异步通知成功,详细信息:"+inputString.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return WXPayUtil.mapToXml(map);
    }

    /*查询支付结果*/
    @AdminLoginToken
    @ResponseBody
    @GetMapping("/chargeResult")
    public AjaxResult chargeResult(HttpServletRequest request,@RequestParam("orderID") Integer order_id) {
        DjbAdmin admin = (DjbAdmin) request.getAttribute("admin");
        DjbTrade trade = tradeMapper.selectDjbTradeById(order_id);
        if(trade==null || !trade.getUserId().equals(admin.getId())){
            return AjaxResult.error("订单号错误");
        }
        if (SYS_YES==trade.getStatus()) {
            return AjaxResult.success("支付成功");
        }
        /*查询支付配置*/
        if ("微信".equals(trade.getPayType())) {
            String appKey ="chargeConfig.getWxAppkey()";
            String appid = "chargeConfig.getWxAppid()";
            String mch_id = "chargeConfig.getWxMchid()";
            Map<String, String> reqData = new HashMap<>();
            reqData.put("out_trade_no", String.valueOf(order_id));
            reqData.put("appid", appid);
            reqData.put("mch_id", mch_id);
            Map<String, String> return_map= null;
            try {
                return_map = WXPayUtil.queryOrder(reqData,appKey);
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (!return_map.get("return_code").equals("SUCCESS") ||!return_map.get("result_code").equals("SUCCESS")||!return_map.get("trade_state").equals("SUCCESS")) {
                return AjaxResult.error("支付失败");
            }
            int order_amount = Integer.parseInt(return_map.get("total_fee"));
            if(order_amount != trade.getMoney()){
                return AjaxResult.error("支付失败");
            }
            /*业务处理*/
            if(!handleChargeOrder(String.valueOf(order_id),return_map.get("transaction_id"))){
                return AjaxResult.error("支付失败");
            }
            return AjaxResult.success("支付成功");
        } else {
//            CertAlipayRequest certAlipayRequest = new CertAlipayRequest();
//            certAlipayRequest.setServerUrl("https://openapi.alipay.com/gateway.do");  //gateway:支付宝网关（固定）https://openapi.alipay.com/gateway.do
//            certAlipayRequest.setAppId("2021002146673802");  //APPID 即创建应用后生成,详情见创建应用并获取 APPID
//            certAlipayRequest.setPrivateKey("MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCBpjChz+/qkdoLHPjhl3U62G0jFtgq/39ApGmjxAoG+9FamKdb1QQYkmQDSqids6dlzZY/1sgQZe4csLnRmV+onkwd6pReyknXa9R44jl1lFPKEQ8ZS17H+7XJejoiwLx9iN217fCpuaxIeFWM0DgBYt2T2LMqG6zHKO9hk5x6gRonTN1fhvUeI4/k4deBS4XKi5jXNFQPKPmOLWF0GfA5dxOmUDwGTSHNsFnEST3GHBWHDH7ZpbI3sEXf3/ZDCdZGKyqNLd4NVuy/ptuEyR4uZhlLvQCiR2mC8IWbTBoBCFolWRZLcEhV3kutNeUOs1aLc0+yXyKK7YAKYML9Iw0BAgMBAAECggEAaFttKdJGO3nLGMbpTiyroAI1Vtk8ht/BfjbZEYjqyVRI37Oggrqj4WN0PXIK52WEiN1C43/u6cQiNdXKvHvIE+HXQv1fEC2j4lJZZDQ0LACIsU2p6aJRWIeze8l2oiKhlipky9wKq5NYqbyyn/W6HuOFl0wGaw57tJOum8xFWBUL9vvNd0Vx5lwPfLwOcNOvlYhnAyCOLTOYKBgNtkq/fAhM+tA/JI4+nK86GvNu2pqI5u7Rad6BqXcn1Ngd7X6cYwEZi4i4t6yV+pNurukGG+jIPXDWiZ+1Sf0czWgq9dsJQmz72L9P4I+7imAgmt8ycN5ghEZdRL5QogF+wAWrAQKBgQDLYw3vuIztaEUJRQ78orgFhHqJ7NzdV06DQEMTgCdpb+tN/v0JuThYw5xh2kbkHEnRV2lB2LwQMW1ocMJ5h1ndWGuVOEDnSPFI/ggahOjyGsNL3dWu5uqr42PbJT6oAlJUcGsOJJh3sNVtRDHuVkNguUt6QSPtYE1juwcIB0muvQKBgQCjL/sy+bvKd8MWnZfx3i14xmCVuyxw+7Uqdv0411Ub/Zvg+FLWbBMjrWD17G2cI162Ke6Xpv+g5hKj6uI6yL+vxyubK+rYyzREmtQ1EcZKpTps9lyfo1bYSVmyaFzWPvkc73HiO4U8L3rfXt1l200wDiwY+1SrDrG10LLxOk/NlQKBgHbbVTqhVCItTCLlq6NyCC6ZQ+80b8IeEnDbbheITf/s+sri18cF6erdrZb1s3X9HhprhcSIPycLa4+cTdotghO7Z2uVq0A+PVtVsTCmOWe6wiSk6ApFQiDfSuy3cE1Ixgo4hCeItV1FBwTK1I8e9FMjFfvE85T2MWO12Z8UezfVAoGAICdHFo8wWj9ouB8LHkQJr59ezoHXytc9pgVV9YowIdjBiv1CzS70QnZaAXq5SieJ9NikQ0tLWPecOqIAO1bstgTHacaoeljnjpD3ORGsgW626VtNesLjTLB/NPDtQeWcjf/773iM0wQD8NkvRG+GcO6J784tq5q0lz9s0q0LplUCgYEAwLrPS69Vlwe6qug1aJtR4EnXiCGiefmcvXM0WEtqr+HoetbkOIC+ognnbV21AmeQcCG7rpjSmE4PQlulKxotqZ5OMfbMdZhBUnMpLqInNuaCHveYHsg45EpFB18V/uPIQbPeiVCIb2UUhpMg5k6Nq721bbHJJxWTUf4Lcm1p6xg=");  //开发者应用私钥，由开发者自己生成
//            certAlipayRequest.setFormat("json");  //参数返回格式，只支持 json 格式
//            certAlipayRequest.setCharset("UTF-8");  //请求和签名使用的字符编码格式，支持 GBK和 UTF-8
//            certAlipayRequest.setSignType("RSA2");  //商户生成签名字符串所使用的签名算法类型，目前支持 RSA2 和 RSA，推荐商家使用 RSA2。
//            if(System.getProperties().getProperty("os.name").toLowerCase().startsWith("win")){
//                certAlipayRequest.setCertPath("X:\\key\\appCertPublicKey_2021002146673802.crt"); //应用公钥证书路径（app_cert_path 文件绝对路径）
//                certAlipayRequest.setAlipayPublicCertPath("X:\\key\\alipayCertPublicKey_RSA2.crt"); //支付宝公钥证书文件路径（alipay_cert_path 文件绝对路径）
//                certAlipayRequest.setRootCertPath("X:\\key\\alipayRootCert.crt");  //支付宝CA根证书文件路径（alipay_root_cert_path 文件绝对路径）
//            }else{
//                certAlipayRequest.setCertPath("/usr/local/alicert/appCertPublicKey_2021002146673802.crt"); //应用公钥证书路径（app_cert_path 文件绝对路径）
//                certAlipayRequest.setAlipayPublicCertPath("/usr/local/alicert/alipayCertPublicKey_RSA2.crt"); //支付宝公钥证书文件路径（alipay_cert_path 文件绝对路径）
//                certAlipayRequest.setRootCertPath("/usr/local/alicert/alipayRootCert.crt");  //支付宝CA根证书文件路径（alipay_root_cert_path 文件绝对路径）
//            }
//            try {
//                AlipayClient alipayClient = getAliPayClient();
//                AlipayTradeQueryRequest AliRequest = new AlipayTradeQueryRequest();
//                JSONObject bizContent = new JSONObject();
//                bizContent.put("out_trade_no", order_id);
//                AliRequest.setBizContent(bizContent.toString());
//                AlipayTradeQueryResponse response = alipayClient.execute(AliRequest);
//                if (!response.isSuccess()) {
//                    return AjaxResult.error("支付失败");
//                }
//                JSONObject js2 = JSONObject.parseObject(response.getBody()).getJSONObject("alipay_trade_query_response");
//                if (!"TRADE_SUCCESS".equals(js2.getString("trade_status"))) {
//                    return AjaxResult.error("支付失败");
//                }
//                double order_amount = Double.parseDouble((String) js2.get("total_amount"));
//                if(order_amount != Double.parseDouble(order.getMoney())){
//                    return AjaxResult.error("支付失败");
//                }
//                if("已支付".equals(order.getStatus())){
//                    return AjaxResult.success("支付成功");
//                }
//                /*业务处理*/
//                DxbUser user = userService.selectDxbUserById(order.getUserId());
//                if(!handleOrder(order,user,js2.getString("trade_no"),0)){
//                    return AjaxResult.error("支付失败");
//                }
//            } catch (AlipayApiException e) {
//                e.printStackTrace();
//            }
            return AjaxResult.success("支付成功");
        }
    }

    /*查询充值消费记录*/
    @AdminLoginToken
    @ResponseBody
    @GetMapping("/tradeList")
    public AjaxResult appQueryOrderPayResult(HttpServletRequest request){
        DjbAdmin admin = (DjbAdmin) request.getAttribute("admin");
        DjbTrade trade = new DjbTrade();
        trade.setDistrictId(admin.getDistrictId());
        List<DjbTrade> list = tradeMapper.selectDjbTradeList(trade);
        if(list.isEmpty()){
            return  AjaxResult.warn("暂无消费记录");
        }
        List<Map<String,Object>> ret = new ArrayList<>();
        for(DjbTrade tmp :list){
            Map<String,Object> map = new HashMap<>();
            map.put("id",tmp.getId());
            map.put("money",tmp.getMoney());
            map.put("order",tmp.getOrderId());
            map.put("time",tmp.getTradeTime());
            map.put("name",tmp.getName());
            map.put("payType",tmp.getPayType());
            map.put("direct",tmp.getDirect());
            map.put("balance",tmp.getBalance());
            ret.add(map);
        }
        return  AjaxResult.success("查询成功",ret);
    }

    /*增值服务开关管理*/
    @PutMapping("/vipSet")
    @ResponseBody
    @AdminLoginToken
    public AjaxResult vipSet(HttpServletRequest request,String type,Integer switchOnOff){
        DjbAdmin admin = (DjbAdmin) request.getAttribute("admin");
        DjbDistrict djbDistrict = districtMapper.selectDjbDistrictById(admin.getDistrictId());
        switch (type){
            case "vipNoAd":
                djbDistrict.setVipNoAd(switchOnOff);
                if(switchOnOff==SYS_YES){
                    /*查询本日是否已扣费*/
                    Date nowDate = DateUtils.getNowDate();
                    DjbTrade check = new DjbTrade();
                    check.setDistrictId(admin.getDistrictId());
                    check.setName("免登记广告");
                    HashMap<String, Object> map = new HashMap<>();
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(nowDate);
                    calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
                    /*今天0点*/
                    Date todayZero = calendar.getTime();
                    map.put("beginTime", DateFormatUtils.format(todayZero,YYYY_MM_DD_HH_MM_SS));
                    check.setParams(map);
                    List<DjbTrade> djbTrades = tradeMapper.selectDjbTradeList(check);
                    if(djbTrades.isEmpty()){
                        djbDistrict.setBalance(djbDistrict.getBalance()-100);
                        DjbTrade djbTrade = new DjbTrade();
                        djbTrade.setChargeId(null);
                        djbTrade.setDistrictId(djbDistrict.getId());
                        djbTrade.setUserId(null);
                        djbTrade.setMoney(100);
                        djbTrade.setCreateTime(nowDate);
                        djbTrade.setPayType("");
                        djbTrade.setStatus(SYS_YES);
                        djbTrade.setName("免登记广告");
                        djbTrade.setDirect("出");
                        djbTrade.setTradeType("消费");
                        djbTrade.setBalance(djbDistrict.getBalance());
                        djbTrade.setTradeTime(nowDate);
                        tradeMapper.insertDjbTrade(djbTrade);
                    }
                }
                break;
            case "vipIncomeSms":
                djbDistrict.setVipIncomeSms(switchOnOff);
                break;
            case "vipOutTimeSms":
                djbDistrict.setVipOutTimeSms(switchOnOff);
                break;
            case "vipCheckPhone":
                djbDistrict.setVipCheckPhone(switchOnOff);
                break;
            case "vipCheckId":
                djbDistrict.setVipCheckId(switchOnOff);
                break;
            default:
                return AjaxResult.error("type类型错误");
        }
        districtMapper.updateDjbDistrict(djbDistrict);
        return AjaxResult.success("修改成功");
    }

    /*增值服务短信模板管理*/
    @PutMapping("/vipSMSTemplateSet")
    @ResponseBody
    @AdminLoginToken
    public AjaxResult vipSMSTemplateSet(HttpServletRequest request,String templateId ){
        DjbAdmin admin = (DjbAdmin) request.getAttribute("admin");
        DjbDistrict djbDistrict = districtMapper.selectDjbDistrictById(admin.getDistrictId());
        DjbSysConfig sysConfig = new DjbSysConfig();
        sysConfig.setSkey("sms.template");
        sysConfig.setType("0");
        sysConfig=djbSysConfigMapper.selectDjbSysConfigList(sysConfig).get(0);
        String content = sysConfig.getValue();
        JSONArray array = JSONArray.parseArray(content);
        for(int i=0;i<array.size();i++){
            JSONObject tmp = array.getJSONObject(i);
            if(!tmp.getString("templateId").equals(templateId)){
                continue;
            }
            if(tmp.getString("type").equals("入场")){
                djbDistrict.setVipIncomeSmsWord(tmp.getString("content"));
                djbDistrict.setVipIncomeSmsId(tmp.getString("templateId"));
            }else{
                djbDistrict.setVipOutSmsWord(tmp.getString("content"));
                djbDistrict.setVipOutSmsId(tmp.getString("templateId"));
            }
        }
        districtMapper.updateDjbDistrict(djbDistrict);
        return AjaxResult.success("修改成功");
    }

    /*短信模板列表*/
    @GetMapping("/SMSTemplateList")
    @ResponseBody
    @AdminLoginToken
    public  AjaxResult SMSTemplateList(){
        DjbSysConfig sysConfig = new DjbSysConfig();
        sysConfig.setSkey("sms.template");
        sysConfig.setType("0");
        sysConfig=djbSysConfigMapper.selectDjbSysConfigList(sysConfig).get(0);
        String content = sysConfig.getValue();
        JSONArray array = JSONArray.parseArray(content);
        return AjaxResult.success("成功",array);
    }

    /*充值支付成功,处理订单业务*/
    private boolean handleChargeOrder(String order_id, String thirdOrderNo) {

        /*业务处理*/
        synchronized(this) {
            DjbTrade trade = tradeMapper.selectDjbTradeById(Integer.valueOf(order_id));
            if(trade.getStatus()==SYS_YES){
                return true;
            }
            DjbDistrict district = districtMapper.selectDjbDistrictById(trade.getDistrictId());
            Date date =DateUtils.getNowDate();
            /*交易成功,处理业务,先变订单状态*/
            trade.setStatus(SYS_YES);
            trade.setPayTime(date);
            trade.setOrderId(thirdOrderNo);
            /*给用户加上剩余金额*/
            DjbChargeGradient chargeGradient = chargeGradientMapper.selectDjbChargeGradientById(trade.getChargeId());
            district.setBalance(district.getBalance()+chargeGradient.getMoney());
            /*修改消费日志表*/
            trade.setStatus(SYS_YES);
            trade.setPayTime(DateUtils.getNowDate());
            tradeMapper.updateDjbTrade(trade);
            districtMapper.updateDjbDistrict(district);
            return true;
        }
    }
}